Hibernate provides the get() and load() methods to retrieve objects from the database using their primary key. While both are used for data fetching, they differ in terms of loading strategy, performance, and exception handling.
- get() fetches data immediately and returns null if the object is not found
- load() uses lazy loading and throws an exception if the object does not exist
get() method
In Hibernate, the get() method is used to retrieve a persistent object from the database using its primary key. It is part of the Session interface and ensures immediate data fetching, either from the cache or database.
- Returns null if the object is not found in the database.
- Checks session cache first, reducing unnecessary database queries.
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.
load() method
The load() method is used to retrieve an object by its primary key, but it returns a proxy instead of the actual object. The real data is fetched only when needed, using lazy loading to improve performance.
- Returns a proxy object and delays database access until the object is used.
- Throws ObjectNotFoundException if the object does not exist in the database.
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.'
get() vs load()
| Feature | get() Method | load() Method |
|---|---|---|
| Database Hit | Fetches data immediately from database | Fetches data only when required (lazy) |
| Return Type | Returns fully initialized object | Returns proxy object |
| If Data Not Found | Returns null | Throws ObjectNotFoundException |
| Performance | Slightly slower due to immediate fetch | Faster due to lazy loading |
| Use Case | Used when record existence is uncertain | Used when record is guaranteed to exist |
| Exception | Does not throw exception | Throws exception if object not found |