Hibernate load() and get(): What’s the Difference?
Two commonly used methods in Hibernate for retrieving objects from the database are load() and get(). Though they appear similar, they exhibit distinct differences in behaviour and use cases. This article explores these differences in detail.
1. load()
Method
The load()
method is used to retrieve an entity from the database by its primary key. However, it does so lazily, which means it returns a proxy of the entity instead of the actual entity itself. The actual database query is executed only when a property of the entity is accessed.
1.1 Characteristics of load()
- Lazy Initialization: Returns a proxy without hitting the database immediately.
- Throws an Exception: Throws an
ObjectNotFoundException
if the entity is not found. - Efficient for Read-Only Operations: Useful when you need a reference to an entity to set associations without requiring the entity’s actual data.
1.2 Example of load() in Hibernate
User Entity: Let’s define a simple User
entity.
@Entity @Table(name = "users") public class User implements Serializable { @Id private Long id; private String name; private String email; // 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
Here is an example demonstrating the use of load()
public class HibernateLoadExample { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Long userId = 3L; // use load method User user = session.load(User.class, userId); System.out.println("User loaded, but not initialized yet."); System.out.println("User name: " + user.getName()); // Triggers database query } }
In this example, we use the load()
method to retrieve a User
entity with a specific ID (3L). The key characteristic of load()
is its lazy initialization. When session.load(User.class, userId)
is called, Hibernate returns a proxy object rather than executing a database query immediately. The proxy object represents the User
entity and will defer loading the actual data until a property of the entity is accessed.
Output When an ID is Found:
When the entity with the specified ID (1L) exists in the database, accessing a property of the proxy object, such as user.getName()
, triggers a database query to load the actual data of the User
entity. The console will print the following:
Output When an ID is Not Found:
If the entity with the specified ID does not exist in the database, accessing any property of the proxy object will result in an ObjectNotFoundException
. The console will print the stack trace of the exception:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=? Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.jcg.hibernateloadexample.User#30]
2. get()
Method
The get()
method retrieves an entity from the database immediately. It directly hits the database and returns the actual entity object. When you call get(class, id)
, Hibernate performs the following actions:
- Checks the Session Cache: It first looks for the object identified by the provided identifier in the Hibernate session cache. If the object exists in the cache, it’s returned directly, avoiding a database hit.
- Fetches from Database (if not in Cache): If the object is not found in the cache, Hibernate fires a database query to retrieve the data based on the identifier.
- Returns the Object (or Null): Upon successful retrieval,
get()
returns the fully initialized object. If no object exists with the given identifier,get()
returnsnull
.
2.1 Characteristics of get()
- Immediate Database Hit: Executes the query and retrieves the entity immediately.
- Returns Null: Returns
null
if the entity is not found. - Eager Initialization: Useful when you need the entity’s data immediately.
2.2 Example of get() in Hibernate
Here is an example demonstrating the use of get()
public class HibernateGetExample { public static void main(String[] args) { // Setup SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); // Begin transaction session.beginTransaction(); // Get entity Long entityId = 1L; User entity = session.get(User.class, entityId); System.out.println("Entity found: " + entity.getName()); } }
In this example, we use the get()
method to retrieve a User
entity with a specific ID (1L). The get()
method immediately executes a database query to fetch the entity’s data and returns the actual User
object. This method is not lazy and directly interacts with the database.
Output When an ID is Found:
When the entity with the specified ID (1L) exists in the database, the get()
method retrieves the entity immediately. The console will print the following:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=? Entity found: John Doe
This output indicates that the User
entity was successfully retrieved.
Output When ID is Not Found:
If the entity with the specified ID does not exist in the database, the get()
method returns null
. The console will print the following:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=? Exception in thread "main" java.lang.NullPointerException
3. Key Differences
Here is a comparison of the load()
and get()
methods in Hibernate.
Feature | load() | get() |
---|---|---|
Initialization | Lazy (returns a proxy) | Eager (retrieves the actual entity) |
Database Query | Deferred until a property is accessed | Executed immediately |
Behaviour if Entity Not Found | Throws ObjectNotFoundException | Returns null |
Use Case | When the entity is expected to exist and lazy loading is acceptable | When immediate access to entity data is needed |
Performance Impact | May improve performance due to deferred loading | Immediate impact due to instant query |
4. Conclusion
In this article, we explored the differences between Hibernate’s load()
and get()
methods. We discussed how load()
provides lazy initialization, returning a proxy and throwing an exception if the entity is not found. On the other hand, get()
retrieves the entity immediately, returning null
if the entity is absent, which is useful when the entity’s data is required right away.
5. Download the Source Code
This article explored the difference between Hibernate load() and get() methods.
You can download the full source code of this example here: hibernate load get difference