Hibernate – Difference between session’s get() and load()

Session.Load()

1. If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null.

try {
    transaction = session.beginTransaction();
    Employee employee = (Employee) session.get(Employee.class, 2L);
    if(employee != null) {
        System.out.println("Name " + employee.getFirstName());
    }
    transaction.commit();
} catch(ObjectNotFoundException onfe) {
    e.printStackTrace();
} 

If no row is found, it throws ObjectNotFoundException

2. The load() method may return a proxy instead of a real persistent instance, allowing lazy initialization and thus better performance . A proxy is a placeholder that triggers the loading of the real object when it’s accessed for the first time.

Employee employee = (Employee) session.load(Employee.class, 1);
Phone phone = new Phone();
phone.setType("Office");
phone.setNumber("1234567890");
phone.setEmployee(employee);
session.save(phone);

Since load() method return a proxy object, Hibernate will not hits database to access Employee details.

Output is as follows :

Hibernate: insert into PHONE (EMPLOYEE_ID, Number, Type) values (?, ?, ?)

Session.Get()

1. The get() method returns null if the object can’t be found.

try {
    transaction = session.beginTransaction();
    Employee employee = (Employee) session.get(Employee.class, 2L);
    if(employee != null) {
        System.out.println("Name " + employee.getFirstName());
    }
    transaction.commit();
} catch(HibernateException he) {
    e.printStackTrace();
} 

If no row is found, it returns null.

2. The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings.

Employee employee = (Employee) session.get(Employee.class, 1);
Phone phone = new Phone();
phone.setType("Office");
phone.setNumber("1234567890");
phone.setEmployee(employee);
session.save(phone);

In session.get(), Hibernate will hit the database to retrieve the Employee object and put it as a reference to Phone object.

Output is as follows :

Hibernate: select employee0_.EMPLOYEE_ID as EMPLOYEE1_0_0_, employee0_.Name as Name0_0_ from EMPLOYEE employee0_ where employee0_.EMPLOYEE_ID=?
Hibernate: insert into PHONE (EMPLOYEE_ID, Number, Type) values (?, ?, ?)

No comments yet.

Leave a Reply