Java.Hibernate.Beginner.What is the difference between load() and get() methods?

🔹 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:

Featureget()load()
BehaviorEagerly fetches entity immediatelyReturns proxy; lazy fetches on property access
If not foundReturns nullThrows ObjectNotFoundException when accessed
Return typeReal entity instanceProxy object
Use caseWhen entity may or may not existWhen 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.

This entry was posted in Без рубрики. Bookmark the permalink.