Differences
Aspect | get() | load() |
Retrieval Strategy | Eager 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 called | Only when you access a non-identifier property (lazy init) |
Return type | Actual object or null | Proxy object (subclass proxy) |
What if object not found? | Returns null | Throws ObjectNotFoundException |
Use case | When you’re not sure if the object exists or you need it right now | When you are sure the object exists or want to defer loading |
Proxy creation | No proxy; returns real object | Returns a proxy without hitting DB |
Initialization | Fully initialized object | Uninitialized 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.