Reputation: 222
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?
Upvotes: 5
Views: 15072
Reputation: 705
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.
Upvotes: 10
Reputation: 5067
In hibernate all the fields will be mapped if not described in any other way. So one can point to the ORM mapper not to map given fields to the DB by using the
[@Transient][1] annotation in case JPA is used
or even the **transient** keyword from java - careful when using this one, it will prevent the given field to be serialized
Upvotes: 2
Reputation: 1186
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)
Upvotes: 4
Reputation: 897
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.
Upvotes: 1