Open In App

Hibernate – get() and load() Method

Hibernate is a Java framework that provides a powerful set of tools for persisting and accessing data in a Java environment. It is often used in conjunction with Spring. Spring and Hibernate are both widely used in the Java community, and they can be used together to build powerful and efficient Java-based applications.

Let’s deal with Fetching objects in Spring Hibernate:

Hibernate provides different methods to fetch data from the database.



  1. get()
  2. load()

1. get() method

Example:




// Open a session
Session session = sessionFactory.openSession();
 
// Begin a transaction
Transaction transaction = session.beginTransaction();
 
// Retrieve the object using the primary key
Customer customer = (Customer) session.get(Customer.class, 1L);
 
// Commit the transaction
transaction.commit();
 
// Close the session
session.close();

In this example, the get() method is used to retrieve a Customer object with a primary key of 1. The object is then cast to the Customer class and stored in the custom variable.



2. load() method

Example:




Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
 
// Load the entity with the identifier 1
Employee employee = (Employee) session.load(Employee.class, 1L);
 
// Print out the employee's name
System.out.println(employee.getName());
 
transaction.commit();
session.close();

In this example, the load() method is used to retrieve an Employee object with a primary key of 1. The object is then cast to the Employee class and stored in the employee variable and printed the employee object.


Article Tags :