Hibernate session differences between load() and get() - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Differences between load() and get() method is one of the most popular interview question in hibernate. Irrespective of experience or fresher, every person will face this question in telephonic or face to face interview.
Not only the interview point of view, in order to understanding the internals of hibernate everybody should aware of the differences between load() and get() methods.
In order to get the details from the database in hibernate, we can call either load() or get() method. By using the load() or get() method we can load (read) the data from the database.
The load and get methods are both looking like a same, and also these two are generates same output. But the functionality wise there are few differences in internally.
In this tutorial we will discuss all possible differences between load() and get() methods with examples.
Before going to discuss about the differences directly, It is mandatory to know what exactly are the load and get methods and how they are working internally.
In order to get the details from the database, we can use the load() method. The load is a instance method which is coming from the hibernate Session object. We can call the load() with two parameters.
session.load(Class class, Serializable id);
session.load(String classname, Serializable id);
By using the above two methods we can load the data from the database. When ever the load() method is called, the hibernate creates a proxy object of a POJO class (provided as parameter), and it will set the id to the proxy object, then it returns the proxy object to the program. Based on the operations performed on the proxy object, the hibernate will decide whether to go cache or database to load the data. This process is called lazy loading. When we access non-id property (not a primary key) of proxy object then hibernate first goes to first level cache and if that object doesn’t available in the cache then hibernate goes to database for loading an object.
Example: Student.java
package com.onlinetutorialspoint.pojo;

public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer rollNumber;

    public Student() {
    }

    public Student(Integer id, String name, Integer rollNumber) {
        this.id = id;
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getRollNumber() {
        return this.rollNumber;
    }

    public void setRollNumber(Integer rollNumber) {
        this.rollNumber = rollNumber;
    }

}

Creating Mapping File Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 10, 2015 11:42:29 AM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
  <class catalog="onlinetutorialspoint" name="com.onlinetutorialspoint.pojo.Student" table="student">
    <id name="id" type="java.lang.Integer">
      <column name="id"/>
      <generator class="identity"/>
    </id>
    <property name="name" type="string">
      <column length="50" name="name"/>
    </property>
    <property name="rollNumber" type="java.lang.Integer">
      <column name="rollnumber"/>
    </property>
  </class>
</hibernate-mapping>

Create a Main class DbOperations.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DbOperations {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Object o = session.load(Student.class, 101);
        Student s = (Student) o;
//         For getting the Id property hibernate will not go to Cache or Database.
//         It will take from the Proxy.
        System.out.println("StudentId : " + s.getId());

//         As name is a non-id property, hibernate first checks in cache,
//         If the value doesn't found in the cache then it will go to data base and fetch the values
        System.out.println("Student Name : " + s.getName());

    }
}

Output :
If we observe the output, after printing the StudentId (Id Property)  hibernate insert statements will be executed. Hence while loading the load() method hibernate will create the proxy object and assigned id to that proxy.
When ever we ask for id property it will take from the proxy only, this process is called as lazy loading. If we ask for non-id properties, then it will goto first level of cache or Database. If the corresponding Object is not found in the database, it returns (load() method) ObjectNotFoundException. Example :
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DbOperations {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Object o = session.load(Student.class, 102);
        Student s = (Student) o;
//         For getting the Id property hibernate will not go to Cache or Database.
//         It will take from the Proxy.
        System.out.println("StudentId : " + s.getId());

//         As name is a non-id property, hibernate first checks in cache,
//         If the value doesn't found in the cache then it will go to data base and fetch the values, If //         it doesn't exist even in database throws ObjectNotFoundException
        System.out.println("Student Name : " + s.getName());

    }
}


Output :
Like wise load() method, in order to get the details from the database we can use the get() method as well. We can call the get() method with two parameters.

session.get(Class class,Serializable id);
session.get(String className,Serializable id);

session.get(Class class,Serializable id);
session.get(String className,Serializable id);
When we call the get() method, then hibernate first goes to first level cache and if that object doesn’t exist in the first level cache then it goes to database and loads the object from database. If Id doesn’t exist in the database, then get() method returns null. When get() method is called no proxy object is created, hence it is called as early loading.
Example :
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DbOperations {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Object o = session.get(Student.class, 101);
    }
}


Output :
On the above example, we didn’t do any operations on the “o”. We didn’t even type cast it, but the hibernate directly went to database and get the details from the database and stored the details in first level cache.
If we use the object “o” the details are getting from the cache.
Example :
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DbOperations {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();
        Object o = session.get(Student.class, 101);
        Student student = (Student) o;
        System.out.println("Student Id : " + student.getId());
        System.out.println("Student Name : " + student.getName());
        System.out.println("Student rollNumber : " + student.getRollNumber());
    }
}


Output :

 When calling the load() method hibernate creates an proxy object and returns the proxy object, but  in the case of get() method there is no concept called proxy it directly hit the database.
load() method loads an object lazily, where as get() method loads an object early.
performance point of view load() method is recommended when compared to get() method.
If the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null.

 When calling the load() method hibernate creates an proxy object and returns the proxy object, but  in the case of get() method there is no concept called proxy it directly hit the database.
load() method loads an object lazily, where as get() method loads an object early.
performance point of view load() method is recommended when compared to get() method.
If the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null.
Happy Learning 🙂


sessionget() Example with Maven

File size: 29 KB
Downloads: 785


Hibernate cache first level example
Difference between update vs merge in Hibernate example
hibernate update query example
Different types of Object States in Hibernate
Top 7 Interview Questions in Hibernate
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
Generator Classes in Hibernate
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
Singleton Hibernate SessionFactory Example
Hibernate Projection with Example
Hibernate Interceptor Example

Hibernate cache first level example
Difference between update vs merge in Hibernate example
hibernate update query example
Different types of Object States in Hibernate
Top 7 Interview Questions in Hibernate
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
Generator Classes in Hibernate
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
Singleton Hibernate SessionFactory Example
Hibernate Projection with Example
Hibernate Interceptor Example






raviteja
March 20, 2018 at 4:06 am - Reply 

in getCurrentSession of session object load it works or not?









raviteja
March 20, 2018 at 4:07 am - Reply 

get and load methods can check the l2 or sechond level cache or not?










raviteja
March 20, 2018 at 4:06 am - Reply 

in getCurrentSession of session object load it works or not?




in getCurrentSession of session object load it works or not?





raviteja
March 20, 2018 at 4:07 am - Reply 

get and load methods can check the l2 or sechond level cache or not?




get and load methods can check the l2 or sechond level cache or not?
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache