Get vs Load in Hibernate with example

Let us understand about GET and LOAD methods in Hibernate


The most widely asked and popular question in Hibernate is “Difference between Get and Load methods”.

Most of the developers use these methods alternatively but there is a substantial difference between these methods and one should use the right method in right situation.

Session.get() and session.load() methods are declared in session.

End use of both the methods is to retrieve the object(single row) from the DB.

Lets understand these 2 methods in detail and also their differences and when to use them

Get:

When we use session.get() method, it will hit the DB immediately and returns the real object from DB.

If there is no row corresponding to requested identifier exists , it will return NULL.

hibernate_get.

Load:

When we use session.load() method, it will always return a proxy object without hitting the DB.

Proxy object is a temporary object which does not have any values assigned to it except primary key or identifier value.

If there is no row corresponding to requested identifier exists , then it will throw “ObjectNotFoundException”.

Hibernate_load

Let us implement the same and test it through example

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure

Get_Load_proj_stru

Step 2

Update pom.xml with Hibernate and Mysql dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>HibernateMergeUpdate</groupId>
  6.   <artifactId>HibernateMergeUpdate</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>HibernateMergeUpdate</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.     <dependency>
  19.       <groupId>junit</groupId>
  20.       <artifactId>junit</artifactId>
  21.       <version>3.8.1</version>
  22.       <scope>test</scope>
  23.     </dependency>
  24.     <dependency>
  25.             <groupId>org.hibernate</groupId>
  26.             <artifactId>hibernate-core</artifactId>
  27.             <version>5.2.6.Final</version>
  28.         </dependency>
  29.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  30.         <dependency>
  31.             <groupId>mysql</groupId>
  32.             <artifactId>mysql-connector-java</artifactId>
  33.             <version>6.0.5</version>
  34.         </dependency>
  35.   </dependencies>
  36. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>HibernateMergeUpdate</groupId>
  <artifactId>HibernateMergeUpdate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HibernateMergeUpdate</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
  </dependencies>
</project>

Step 3

Create Employee class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Employee")
  12. public class Employee {
  13.     @Id
  14.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  15.     @Column(name = "Employee_Id")
  16.     private int employeeId;
  17.    
  18.     @Column(name = "FirstName")
  19.     private String firstName;
  20.    
  21.     @Column(name = "LastName")
  22.     private String lastName;
  23.    
  24.     @Column(name = "Age")
  25.     private int age;
  26.    
  27.     @Column(name = "Education")
  28.     private String education;
  29.    
  30.     @Column(name = "Salary")
  31.     private int salary;
  32.    
  33.     public int getEmployeeId() {
  34.         return employeeId;
  35.     }
  36.     public void setEmployeeId(int employeeId) {
  37.         this.employeeId = employeeId;
  38.     }
  39.     public String getFirstName() {
  40.         return firstName;
  41.     }
  42.     public void setFirstName(String firstName) {
  43.         this.firstName = firstName;
  44.     }
  45.     public String getLastName() {
  46.         return lastName;
  47.     }
  48.     public void setLastName(String lastName) {
  49.         this.lastName = lastName;
  50.     }
  51.     public int getAge() {
  52.         return age;
  53.     }
  54.     public void setAge(int age) {
  55.         this.age = age;
  56.     }
  57.     public String getEducation() {
  58.         return education;
  59.     }
  60.     public void setEducation(String education) {
  61.         this.education = education;
  62.     }
  63.     public int getSalary() {
  64.         return salary;
  65.     }
  66.     public void setSalary(int salary) {
  67.         this.salary = salary;
  68.     }
  69. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private int employeeId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private int age;
	
	@Column(name = "Education")
	private String education;
	
	@Column(name = "Salary")
	private int salary;
	
	public int getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
}


We have specified Primary key as employeeId and generator class as “sequence” for automatic primary key generation.

Step 4

Create hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.     <session-factory>
  9.  
  10.         <!-- Database connection properties -->
  11.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.         <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.         <property name="connection.username">root</property>
  14.         <property name="connection.password">root</property>
  15.  
  16.         <!-- JDBC connection pool (using the built-in) -->
  17.         <property name="connection.pool_size">100</property>
  18.  
  19.         <!-- SQL dialect -->
  20.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.         <!-- Disable the second-level cache -->
  23.         <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.         <!-- Echo all executed SQL to stdout -->
  26.         <property name="show_sql">true</property>
  27.  
  28.         <!-- Format the generated Sql -->
  29.         <property name="format_sql">true</property>
  30.  
  31.         <!-- Dont Drop and re-create the database schema on startup,Just update
  32.             it -->
  33.         <property name="hbm2ddl.auto">update</property>
  34.  
  35.         <mapping class="com.kb.model.Employee" />
  36.  
  37.     </session-factory>
  38.  
  39. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- Database connection properties -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<!-- JDBC connection pool (using the built-in) -->
		<property name="connection.pool_size">100</property>

		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>

		<!-- Format the generated Sql -->
		<property name="format_sql">true</property>

		<!-- Dont Drop and re-create the database schema on startup,Just update 
			it -->
		<property name="hbm2ddl.auto">update</property>

		<mapping class="com.kb.model.Employee" />

	</session-factory>

</hibernate-configuration>


We have defined all the database configuration in this file

hbm2ddl.auto property is defined in the config file which helps in automatic creation of tables in the database based on the mapping.

We have also provided the mapping class name using “mapping” tag.

Step 5

Create Hibernate util class

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 6

Create PopulateData.java file to Populate Employee Table with initial data

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6.  
  7. import com.kb.model.Employee;
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class PopulateData {
  11. public static void main(String[] args) {
  12.  
  13.     // Get session factory using Hibernate Util class
  14.     SessionFactory sf = HibernateUtil.getSessionFactory();
  15.     // Get session from Sesson factory
  16.     Session session = sf.openSession();
  17.  
  18.     // Begin transaction
  19.     Transaction t = session.beginTransaction();
  20.    
  21.     //Create Employee  data
  22.     Employee employee1 = new Employee();
  23.     employee1.setFirstName("John");
  24.     employee1.setLastName("KC");
  25.     employee1.setAge(28);
  26.     employee1.setEducation("PG");
  27.     employee1.setSalary(25000);
  28.    
  29.     Employee employee2 = new Employee();
  30.     employee2.setFirstName("Jacob");
  31.     employee2.setLastName("JC");
  32.     employee2.setAge(30);
  33.     employee2.setEducation("PG");
  34.     employee2.setSalary(30000);
  35.    
  36.     Employee employee3 = new Employee();
  37.     employee3.setFirstName("Martin");
  38.     employee3.setLastName("A");
  39.     employee3.setAge(24);
  40.     employee3.setEducation("UG");
  41.     employee3.setSalary(20000);
  42.    
  43.     Employee employee4 = new Employee();
  44.     employee4.setFirstName("Peter");
  45.     employee4.setLastName("M");
  46.     employee4.setAge(25);
  47.     employee4.setEducation("UG");
  48.     employee4.setSalary(22000);
  49.    
  50.     Employee employee5 = new Employee();
  51.     employee5.setFirstName("Roshan");
  52.     employee5.setLastName("B");
  53.     employee5.setAge(29);
  54.     employee5.setEducation("PG");
  55.     employee5.setSalary(45000);
  56.    
  57.    
  58.     session.save(employee1);
  59.     session.save(employee2);
  60.     session.save(employee3);
  61.     session.save(employee4);
  62.     session.save(employee5);
  63.  
  64.     // Commit the transaction and close the session
  65.     t.commit();
  66.    
  67.     session.close();
  68.     System.out.println("successfully persisted Employee details");
  69.  
  70.    }
  71.  
  72. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class PopulateData {
public static void main(String[] args) {

	// Get session factory using Hibernate Util class
	SessionFactory sf = HibernateUtil.getSessionFactory();
	// Get session from Sesson factory
	Session session = sf.openSession();

	// Begin transaction
	Transaction t = session.beginTransaction();
	
	//Create Employee  data
	Employee employee1 = new Employee();
	employee1.setFirstName("John");
	employee1.setLastName("KC");
	employee1.setAge(28);
	employee1.setEducation("PG");
	employee1.setSalary(25000);
	
	Employee employee2 = new Employee();
	employee2.setFirstName("Jacob");
	employee2.setLastName("JC");
	employee2.setAge(30);
	employee2.setEducation("PG");
	employee2.setSalary(30000);
	
	Employee employee3 = new Employee();
	employee3.setFirstName("Martin");
	employee3.setLastName("A");
	employee3.setAge(24);
	employee3.setEducation("UG");
	employee3.setSalary(20000);
	
	Employee employee4 = new Employee();
	employee4.setFirstName("Peter");
	employee4.setLastName("M");
	employee4.setAge(25);
	employee4.setEducation("UG");
	employee4.setSalary(22000);
	
	Employee employee5 = new Employee();
	employee5.setFirstName("Roshan");
	employee5.setLastName("B");
	employee5.setAge(29);
	employee5.setEducation("PG");
	employee5.setSalary(45000);
	
	
	session.save(employee1);
	session.save(employee2);
	session.save(employee3);
	session.save(employee4);
	session.save(employee5);

	// Commit the transaction and close the session
	t.commit();
	
	session.close();
	System.out.println("successfully persisted Employee details");

   }

}


In this class, we are persisting 5 Employee records

Step 7

Lets Create Main class to perform Get and Load operations

Create GetExample.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5.  
  6. import com.kb.model.Employee;
  7. import com.kb.util.HibernateUtil;
  8.  
  9. public class GetExample {
  10.     public static void main(String[] args) {
  11.         // Get session factory using Hibernate Util class
  12.         SessionFactory sf = HibernateUtil.getSessionFactory();
  13.         // Get session from Session factory
  14.         Session session = sf.openSession();
  15.  
  16.         // Get the Employee details whose Id is 1
  17.         System.out.println("Calling Session.get() method");
  18.         session.get(Employee.class, new Integer(1));
  19.         session.close();
  20.        
  21.     }
  22.  
  23. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class GetExample {
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Session factory
		Session session = sf.openSession();

		// Get the Employee details whose Id is 1
		System.out.println("Calling Session.get() method");
		session.get(Employee.class, new Integer(1));
		session.close();
		
	}

}


In this program, we are calling get() method to retrieve the Employee record, since get() method does not use Proxy ,query will be fired immediately to retrieve the record.

Create LoadExample.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5.  
  6. import com.kb.model.Employee;
  7. import com.kb.util.HibernateUtil;
  8.  
  9. public class LoadExample {
  10.     public static void main(String[] args) {
  11.         // Get session factory using Hibernate Util class
  12.         SessionFactory sf = HibernateUtil.getSessionFactory();
  13.         // Get session from Session factory
  14.         Session session = sf.openSession();
  15.  
  16.         // Load the Employee details whose Id is 1
  17.         System.out.println("Calling Session.load() method");
  18.         session.load(Employee.class, new Integer(1));
  19.         session.close();
  20.        
  21.     }
  22.    
  23.  
  24. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class LoadExample {
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Session factory
		Session session = sf.openSession();

		// Load the Employee details whose Id is 1
		System.out.println("Calling Session.load() method");
		session.load(Employee.class, new Integer(1));
		session.close();
		
	}
	

}


In this program, we are calling load() method to retrieve the Employee record, since load() method uses Proxy ,query will not be fired to retrieve the data from DB.
If we use this object , then only query will be fired to DB.

Create GetExample1.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5.  
  6. import com.kb.model.Employee;
  7. import com.kb.util.HibernateUtil;
  8.  
  9. public class GetExample1 {
  10.  
  11.     public static void main(String[] args) {
  12.  
  13.             // Get session factory using Hibernate Util class
  14.             SessionFactory sf = HibernateUtil.getSessionFactory();
  15.             // Get session from Session factory
  16.             Session session = sf.openSession();
  17.  
  18.             // Get the Employee details whose Id is 1
  19.             System.out.println("Calling Session.get() method");
  20.             Employee employee = (Employee)session.get(Employee.class, new
  21.                                                                             Integer(10));
  22.             System.out.println("Employee Obj --> "+employee);
  23.             session.close();
  24.        
  25.     }
  26. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class GetExample1 {

	public static void main(String[] args) {

			// Get session factory using Hibernate Util class
			SessionFactory sf = HibernateUtil.getSessionFactory();
			// Get session from Session factory
			Session session = sf.openSession();

			// Get the Employee details whose Id is 1
			System.out.println("Calling Session.get() method");
			Employee employee = (Employee)session.get(Employee.class, new 
                                                                            Integer(10));
			System.out.println("Employee Obj --> "+employee);
			session.close();
		
	}
}


In this program, we are calling get() method to retrieve the Employee record whose Id is 10, but in our DB , there is no such record exists.
So get() method returns null.

Create LoadExample1.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5.  
  6. import com.kb.model.Employee;
  7. import com.kb.util.HibernateUtil;
  8.  
  9. public class LoadExample1 {
  10.  
  11.     public static void main(String[] args) {
  12.  
  13.         // Get session factory using Hibernate Util class
  14.         SessionFactory sf = HibernateUtil.getSessionFactory();
  15.         // Get session from Session factory
  16.         Session session = sf.openSession();
  17.  
  18.         // Load the Employee details whose Id is 1
  19.         System.out.println("Calling Session.load() method");
  20.         Employee employee = session.load(Employee.class, new Integer(10));
  21.         System.out.println("Employee Obj --> "+employee);
  22.         session.close();
  23.        
  24.     }
  25. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.kb.model.Employee;
import com.kb.util.HibernateUtil;

public class LoadExample1 {

	public static void main(String[] args) {

		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Session factory
		Session session = sf.openSession();

		// Load the Employee details whose Id is 1
		System.out.println("Calling Session.load() method");
		Employee employee = session.load(Employee.class, new Integer(10));
		System.out.println("Employee Obj --> "+employee);
		session.close();
		
	}
}


In this program, we are calling load() method to retrieve the Employee record whose Id is 10, but in our DB , there is no such record exists.

So load() method throws below exception
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:

Step 8

Run PopulateData.java class to create the initial data

Step 9

Check the output in MYSQL DB

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Select * from Employee;

populateAggregateDataOutput

We can see that Emploeyee table has 5 records.

Step 10

Run GetExample.java

Output

hibernate_get_output

Step 11

Run LoadExample.java

Output

hibernate_Load_output.

Step 12

Run GetExample1.java

Output

hibernate_get_output_1

Step 13

Run LoadExample1.java

Output

hibernate_load_output_1

Note:
Load() method fires query to DB only when the object is used by the application, just like Lazy loading. Get() method fires the query immediately to DB , just like eager loading.


Download this project HibernateGetLoad.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on