Learnitweb

Differences between get() and load() in Hibernate

Differences

Aspectget()load()
Retrieval StrategyEager loading (hits the database immediately)Lazy loading (returns a proxy and hits DB only when needed)
When is the DB hit?Immediately when get() is calledOnly when you access a non-identifier property (lazy init)
Return typeActual object or nullProxy object (subclass proxy)
What if object not found?Returns nullThrows ObjectNotFoundException
Use caseWhen you’re not sure if the object exists or you need it right nowWhen you are sure the object exists or want to defer loading
Proxy creationNo proxy; returns real objectReturns a proxy without hitting DB
InitializationFully initialized objectUninitialized proxy unless accessed

Example

Assume we have an Employee entity with id = 1 in the database.

// get() example
Employee emp = session.get(Employee.class, 1); // hits DB immediately
System.out.println(emp.getName());             // uses the object directly

// load() example
Employee emp = session.load(Employee.class, 1); // does NOT hit DB yet
System.out.println(emp.getName());              // hits DB here

What if the ID doesn’t exist?

Employee emp = session.get(Employee.class, 999);
// emp is null

Employee emp = session.load(Employee.class, 999);
// No exception yet
System.out.println(emp.getName()); // Throws ObjectNotFoundException here

When to use which?

  • Use get() when:
    • You need the object immediately.
    • You are not sure whether the object exists.
    • You want to avoid exceptions.
  • Use load() when:
    • You are sure the object exists.
    • You want performance through lazy loading.
    • You want to use proxies for read-only operations or deferred initialization.