Using hibernate with java, do we need to map all the java pojo fields to the Database table columns? Or can we just map only a few fields with few columns?
The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table.
POJO classes are used in hibernate for mapping to database objects. That means all object entities we make in POJO classes will be reflected in a database object. It should not extend classes, implement interfaces, or contain prespecified annotations.
In hibernate, the preffered way to do this is by annotations. Annotations are piece of code that eases our work in mapping classes with tables, and methods with coulmns. Also, rows of tables to the Objects of the classes. This is also possible in XML mapping, but I've used annotations more.
Yes you can map few fields of your Pojo class to your table columns. Not a Problem. It will successfully store the data in the DB.
Example:
Below is StudentData Pojo
public class StudentData1 {
private String name;
private int id;
private String name1;
//setters & getters
}
And HBM file:
<class name="example.StudentData" table="StudentData">
<id name="id" column="pid" >
<generator class="assigned" />
</id>
<property name="name" column="pname" />
</class>
And the CFG file is
<mapping resource="StudentData.hbm.xml"/>
And the Main Class is
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = factory.openSession();
StudentData1 s = new StudentData1();
s.setId(1);
s.setName("iPhone");
Transaction tx = session.beginTransaction();
session.save(s);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
You can run this code it, will execute and store only two fields.
I assume you want to persist only a subset of a class's fields in the database.
You can use the @Transient
annotation to mark fields you do not wish to be persisted.
Warning: make sure to respect that those fields might not be initialized (since there is no value for them in the DB when they are loaded)
I didn't check it but I don't see why couldn't you leave some fields not mapped, especially if they do not exist as a column in the table. Of course in some cases you need to map a column to the field, e.g. when column cannot be null, during saving you will get an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With