difference Hibernate get() and load() method
In Hibernate, both get and load methods are used to retrieve an entity from the database, but they have significant differences in terms of behavior and usage.
1. get() Method:
- Immediate Fetch: The get() method immediately hits the database and retrieves the entity or returns null if the entity does not exist.
- Returns Actual Object or null: If the entity is not found, it returns null.
- Use Case: Typically used when you are not sure if the entity exists or when you need to check if the entity exists.
2. load() Method:
- Lazy Fetch: The get and load method returns a proxy object without hitting the database immediately. It only hits the database when a property of the object is accessed.
- Throws Exception: If the entity does not exist, it throws an ObjectNotFoundException when the entity is first accessed.
- Use Case: Typically used when you are sure that the entity exists and you want to optimize performance by delaying the database hit.
Table of Contents
Key Differences get and load
- Fetch Timing: get() retrieves the entity immediately, while load() retrieves it lazily.
- Return Value: get() returns null if the entity is not found, while load() throws an exception.
- Proxy Object: load() returns a proxy object that is initialized only when accessed.
get and load Example
Here is an example demonstrating the difference between get and load:
Create Hibernate Configuration File (hibernate.cfg.xml):
1. Create Hibernate Configuration File (hibernate.cfg.xml):
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify the HBMs and annotated classes here -->
<mapping class="com.example.MyEntity"/>
</session-factory>
</hibernate-configuration>
Create Entity Class (MyEntity.java):
2. Create Entity Class (MyEntity.java):
java
package com.example;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class MyEntity {
@Id
private Long id;
private String name;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Load Configuration and Build SessionFactory
3. Load Configuration and Build SessionFactory (HibernateUtil.java):
java
package com.example;
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, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Using get() and load() Methods:
4. Using get() and load() Methods:
java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.ObjectNotFoundException;
public class Main {
public static void main(String[] args) {
// Get the SessionFactory
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
// Open a session
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
// Start a transaction
transaction = session.beginTransaction();
// Using get() method
MyEntity entityGet = session.get(MyEntity.class, 1L);
if (entityGet != null) {
System.out.println("Entity found using get(): " + entityGet.getName());
} else {
System.out.println("Entity not found using get()");
}
// Using load() method
try {
MyEntity entityLoad = session.load(MyEntity.class, 1L);
System.out.println("Entity found using load(): " + entityLoad.getName());
} catch (ObjectNotFoundException e) {
System.out.println("Entity not found using load()");
}
// Commit the transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
// Close the session
session.close();
}
}
}