Hibernate Load Vs Get Differences

Programmers new to hibernate may face dilemmas trying to understand the subtle differences between hibernate’s get and load methods for retrieving an entity. I remember my struggle to grasp the differences, and thought I would compile the information I got from various web sources into one single post to help out others facing similar issues.

Here is a refresher on how these two methods can be used:

// Open the session
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// Load the Persistent entity using either Get or Load
Item itemByLoad = (Item) session.load(Item.class, new Long(1234));
//or should you use???
Item itemByGet = (Item) session.get(Item.class, new Long(1234));
tx.commit();
session.close();

Below we explore the various aspects of Load/Get operations in Hibernate to understand their differences.

Javadoc

Querying for an instance that doesn’t exist in the database

Querying for an instance that exists in the database

Accessing properties from a detached entity

An entity becomes detached when it is outside of an active Hibernate Session.

session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
session.getTransaction().commit();
System.out.println(user.getPassword());

The above generates org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Typical Usage Guidelines

Example

The following illustrates the difference between Get/Load operation.

public class PetService {
	public void purchasePet(Long ownerUserId, Long petId) {
		Session session = getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		User owner = session.get(User.class, ownerUserId);
		/* or, using load 
		 * User owner = session.load( User.class, ownerUserId); */

		Pet purchasedPet = session.get(Pet.class, petId);
		/* or using load Pet 
		 * purchasedPet = session.load( Pet.class, petId); */

		owner.setPet(purchasedPet);

		tx.commit();
		session.close();
	}
}

Also see my other post regarding Hibernate Derived Properties.