Monday, July 28, 2014

Mapping Class in Hibernate

The basic notion of ORM is mapping between class and table. A class is considered to be an entity when it gets the Entity annotation.
Entity
@Entity

public class Student {

We can provide a name to an entity. By default the name is the class name. We can give another name to entity so that conflicts do not occur because of same name entity sitting in different package
@Entity(name="anotherStudent")

public class Student {

By default this entity gets mapped to a table with same name. If we want to specify the table name explicitly
@Entity

@Table(name="Student")

public class Student {

Dynamic SQL Generation
Hibernate by default generates the SQL for CRUD right in the beginning. This also means that even if we just update one property of the entity, still the update is issued for all the properties. If we want hibernate to generate SQL at runtime only taking care of changed entity only than use Entity annotation coming from hibernate.
Let's introduce a property in Student class age
@Entity

@Table(name="Student")

public class Student {

    

    //Id will correspond the primary key in the database
    private Long id;
    protected String name;
    protected Integer age;
    
       //Getters and Setters
        ...
    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {

        this.age = age;

    }

        ...

Persist the student by making a new Student object and setting show_sql true.
Student student = new Student();

student.setName("oyeJava");

Long studentId = (Long)session.save(student);

The SQL generated by hibernate as seen in console is
insert into Student (STUDENT_ID, age, name) values (null, ?, ?)
Note that though the age has not been set but still the SQL contains the age parameter. Now let's introduce the Entity annotation from Hibernate so that we ask hibernate to generate the SQL at runtime rather than using the pre generated CRUD statement
//dynamicInsert - Include only those properties which are not null in inserting the data

//dynamicUpdate - Include only those properties which have changed

@Entity

@org.hibernate.annotations.Entity(

    dynamicInsert=true,
    dynamicUpdate=true)
public class Student {

The SQL generated at console is
insert into Student (name, STUDENT_ID) values (?, null)
Note that the age field is absent. This is useful when the table has very large number of columns and modification and insertion is done only on smaller number of columns.
Immutability
When we know that an entity is not going to change at runtime. For example older messages fetched from database, than we can ask hibernate to not to do dirty checking for it. This also results in better performance.
@org.hibernate.annotations.Entity(

    dynamicInsert=true,

    dynamicUpdate=true,

    mutable=false

)
public class Student {

More write-ups on Hibernate

No comments:

Post a Comment