🔹 1️⃣ session.get()
✅ Loads the entity immediately from the database or session cache.
✅ Returns the real object, not a proxy.
✅ Returns null
if the entity with the given ID doesn’t exist — safe for optional lookups.
✅ Eager behavior → triggers a database query right away (unless already in first-level cache).
Example:
User user = session.get(User.class, 1L); // hits DB immediately
if (user == null) {
System.out.println("User not found!");
}
🔹 2️⃣ session.load()
✅ Returns a proxy object (a lightweight placeholder) without immediately querying the database.
✅ Only queries the database when you actually access a property of the proxy (lazy initialization).
✅ Throws ObjectNotFoundException
if the entity doesn’t exist when accessing properties.
✅ Useful when you know the entity must exist, or you want to delay the database hit until necessary.
Example:
User user = session.load(User.class, 1L); // returns proxy
System.out.println(user.getUsername()); // triggers DB fetch or throws exception if not found
🔹 Key differences summarized:
Feature | get() | load() |
---|---|---|
Behavior | Eagerly fetches entity immediately | Returns proxy; lazy fetches on property access |
If not found | Returns null | Throws ObjectNotFoundException when accessed |
Return type | Real entity instance | Proxy object |
Use case | When entity may or may not exist | When entity must exist or for lazy loading |
🔹 Practical advice:
✅ Use get()
when you’re unsure if the entity exists or need immediate data.
✅ Use load()
when you know the entity must exist and want to benefit from lazy loading — but handle potential ObjectNotFoundException
.
✅ Key takeaway:get()
fetches the entity right away and returns null
if not found, while load()
returns a proxy, delaying the query until you access a property — but throws an exception if the entity doesn’t exist.