hiber

Difference between get() and load() in Hibernate With Example

Posted on Updated on

These two methods used to retrieve an Object from DB using Object identifier.

session.get() :  Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)

  • It always hit the database and return the real object, an object that represent the database row, not proxy.
  • If no row found , it return null.

Syntax :

Object get(Class clazz,Serializable id) throws HibernateException

Example :-

Student student0 = new Student("Student1", "Student1-234","Student1@domain.com");
Student student1 = new Student("Student2", "Student2-234","Student2@domain.com");
Student student2 = new Student("Student3", "Student3-234","Student3@domain.com");

Session session = HibernateUtils.getInstance().openSession();
Transaction tx = session.beginTransaction();

session.save(student0);
session.save(student2);
session.save(student1);

Student get_student1 = (Student)session.get(Student.class, 1L);
System.out.println(get_student1);
tx.commit();
session.close();

Generate output: In given generated output, not any select statement get issued even though session.get() is called because Hibernate enabled First Level Session Cache by default, means Student instances i.e student0,studen1 and student2 already exists in current session therefore no need to hit database for these identifiers, requested result return from Session Cache itself.

But when we call session.get() from another session then first it look up  into First Cache if not exist then hit to database in order to poll out corresponding identifier Object.

Hibernate: drop table if exists Student
Hibernate: create table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Student [id=1, name=Student1, rollno=Student1-234, email=Student1@domain.com, enrollmentDate=Tue Feb 23 18:07:16 IST 2016]

session.load() : Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.

You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.

  • It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
  • If no row found, it will throws an ObjectNotFoundException.

Syntax :

Object load( Class theClasss, Serializable id)

Example:- 

Student student0 = new Student("Student1", "Student1-234","Student1@domain.com");
Student student1 = new Student("Student2", "Student2-234","Student2@domain.com");
Student student2 = new Student("Student3", "Student3-234","Student3@domain.com");

Session session = HibernateUtils.getInstance().openSession();
Transaction tx = session.beginTransaction();

session.save(student0);

 tx.commit();
 session.close();
 
 session = HibernateUtils.getInstance().openSession();
 tx = session.beginTransaction();
 
 Student get_student1 = (Student)session.load(Student.class, 1L);
 System.out.println(get_student1);
 
 get_student1 = (Student)session.load(Student.class, 10L); // Throw exception becuase 10 identifier does not exist
 System.out.println(get_student1);
 
 tx.commit();
 session.close();

Generated Output :-

Hibernate: drop table if exists Student
Hibernate: create table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Student [id=1, name=Student1, rollno=Student1-234, email=Student1@domain.com, enrollmentDate=2016-02-23]
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Exception in thread “main” org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.itexperts.hibernate.model.Student#10]
at org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:236)
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:171)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:160)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.itexperts.hibernate.model.Student_$$_javassist_0.toString(Student_$$_javassist_0.java)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at com.itexperts.relationship.example.HibernateTest1.main(HibernateTest1.java:37)

Thanks

See previous article here.

Advertisements