<div dir="ltr" style="text-align: justify;">In hibernate session there are two methods for retrieving object from database one is get() and other load() method. These two methods have been used in the different situations but both are from Session interface and we will call them as session.get() &; session.load(). This is one of the famous hibernate interview questions. Let&#8217;s see differences between them with example.<br />
<b></b></div>
<h2 dir="ltr" style="text-align: justify;"><b>Sample Example Hibernate Application for get() and load() methods</b></h2>
<div dir="ltr" style="text-align: justify;">Consider a Employee class having 3 properties <b>empid</b>, <b>empName</b>, <b>address</b>.</p>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;">
<p><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<h3><b>Example of session.get():</b></h3>
<pre class="highlight">package com.dineshonjava.hibernate; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.boot.Metadata; 
import org.hibernate.boot.MetadataSources; 
import org.hibernate.boot.registry.StandardServiceRegistry; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
 
import com.sdnext.hibernate.tutorial.dto.Employee; 
 
 
public class HibernateTestDemo { 
 
 private static SessionFactory sessionFactory = createSessionFactory(); 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) 
 { 
 Employee employee = null; 
 Session session = sessionFactory.openSession(); 
 Transaction transaction = session.beginTransaction(); 
 transaction.begin(); 
 employee = (Employee) session.get(Employee.class, 1); 
 //get employee object with id 1 
 System.out.println(employee); 
 //update employee address of retrieved object, it immediately update to DB because of get method retrieved actual persistent object 
 employee.setAddress("Noida"); 
 //Here we have updated object 
 System.out.println(employee); 
 
 transaction.commit(); 
 session.close(); 
 sessionFactory.close(); 
 } 
 
 private static SessionFactory createSessionFactory() { 
 if (sessionFactory == null) { 
 StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); 
 Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build(); 
 sessionFactory = metaData.getSessionFactoryBuilder().build(); 
 } 
 return sessionFactory; 
 } 
} 
</pre>
<p><b>Output on console:</b></p>
<pre class="highlight">...................................... 
................................. 
Jan 31, 2017 10:42:58 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation 
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 
Jan 31, 2017 10:42:58 PM org.hibernate.boot.internal.SessionFactoryBuilderImpl$SessionFactoryOptionsStateStandardImpl 
WARN: Unrecognized hbm2ddl_auto value : create | update. Supported values include create, create-drop, update, and validate. Ignoring 
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=? 
Employee [empid=1, empname=Dinesh Rajput, address=New Delhi] 
Employee [empid=1, empname=Dinesh Rajput, address=Noida] 
Hibernate: update EMPLOYEE set ADDRESS=?, EMP_NAME=? where EMPID=? 
...................... 
...................... 
</pre>
<p><b>Explanation:</b><br />
Here when we call session.get() method hibernate will hit the database and returns the original object [ row ], that’s the reason it was generated a query when we update any value of this object. If suppose object of given id does not exist in data base then it return null instead throwing any exception let&#8217;s see as below console output.</p>
<pre class="highlight">...................................... 
................................. 
WARN: Unrecognized hbm2ddl_auto value : create | update. Supported values include create, create-drop, update, and validate. Ignoring 
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=? 
null 
...................... 
...................... 
</pre>
<h3><b>Example of session.load():</b></h3>
<pre class="highlight">package com.dineshonjava.hibernate; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.boot.Metadata; 
import org.hibernate.boot.MetadataSources; 
import org.hibernate.boot.registry.StandardServiceRegistry; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
 
import com.sdnext.hibernate.tutorial.dto.Employee; 
 
 
public class HibernateTestDemo { 
 
 private static SessionFactory sessionFactory = createSessionFactory(); 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) 
 { 
 Employee employee = null; 
 Session session = sessionFactory.openSession(); 
 Transaction transaction = session.beginTransaction(); 
 transaction.begin(); 
 employee = (Employee) session.load(Employee.class, 1); 
 //get employee object with id 1 
 System.out.println(employee); 
 //if object found then update employee address of retrieved the proxy object instead of original object i.e. it does not update to DB 
 employee.setAddress("Noida"); 
 transaction.commit(); 
 session.close(); 
 sessionFactory.close(); 
 } 
 
 private static SessionFactory createSessionFactory() { 
 if (sessionFactory == null) { 
 StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); 
 Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build(); 
 sessionFactory = metaData.getSessionFactoryBuilder().build(); 
 } 
 return sessionFactory; 
 } 
} 
</pre>
<p><b><br />
</b> <b>Output on console:</b></p>
<pre class="highlight">...................................... 
................................. 
WARN: Unrecognized hbm2ddl_auto value : create | update. Supported values include create, create-drop, update, and validate. Ignoring 
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=? 
Employee [empid=1, empname=Dinesh Rajput, address=Noida] 
...................... 
...................... 
</pre>
<p><b>Explanation:</b><br />
When you call session.load() method, it will always return a &#8220;proxy&#8221; object, Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting the database, for example if we call session.load(Employee.class, 1) then hibernate will create one fake Employee object [row] in the memory with id 1, when we made change to property of object it didn&#8217;t update database because of proxy object. So finally we came to know that session.load() will hit the database only when we start retrieving the object (row) values. In case of given id object doesn&#8217;t exist in DB then this method will throw an Exception as below.</p>
<pre class="highlight">...................................... 
................................. 
WARN: Unrecognized hbm2ddl_auto value : create | update. Supported values include create, create-drop, update, and validate. Ignoring 
Hibernate: select employee0_.EMPID as EMPID1_0_0_, employee0_.ADDRESS as ADDRESS2_0_0_, employee0_.EMP_NAME as EMP_NAME3_0_0_ from EMPLOYEE employee0_ where employee0_.EMPID=? 
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.sdnext.hibernate.tutorial.dto.Employee#4] 
 at org.hibernate.boot.internal.StandardEntityNotFoundDelegate.handleEntityNotFound(StandardEntityNotFoundDelegate.java:28) 
 at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:242) 
 at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:159) 
 at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266) 
 at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68) 
 at com.sdnext.hibernate.tutorial.dto.Employee_$$_jvstc72_0.toString(Employee_$$_jvstc72_0.java) 
 at java.lang.String.valueOf(Unknown Source) 
 at java.io.PrintStream.println(Unknown Source) 
 at com.sdnext.hibernate.tutorial.HibernateTestDemo.main(HibernateTestDemo.java:34) 
...................... 
...................... 
</pre>
<p>After discussion of this above example there are following difference we found as pointed below.</p>
<p><b>Session.load(): </b></p>
<ul style="text-align: left;">
<li>It will always return a “proxy” 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.</li>
<li>load() method doesn&#8217;t hit the database.</li>
<li>If no row found , it will throws an ObjectNotFoundException.</li>
</ul>
<p><b>Session.get():</b></p>
<ul style="text-align: left;">
<li>It always hit the database and return the real object, an object that represent the database row, not proxy.</li>
<li>If no row found , it return null.</li>
<li>get() method always hit the database.</li>
<li>It returns real object not proxy.</li>
</ul>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/difference-between-merge-and-update-methods-in-hibernate/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '87'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…