You retrieve an object by its primary key (ID) using either:
1️⃣ session.get()
— recommended for most use cases, or
2️⃣ session.load()
— advanced use cases.
🔹 Using session.get()
- Loads the entity immediately from the database or session cache.
- Returns the entity or
null
if no matching row is found.
Example:
Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // fetch User with ID 1
if (user != null) {
System.out.println("User: " + user.getUsername());
} else {
System.out.println("User not found!");
}
session.close();
🔹 Using session.load()
- Returns a proxy without hitting the database immediately (lazy load).
- Only fetches data from DB if you actually access a property.
- Throws
ObjectNotFoundException
if no matching row exists.
Example:
Session session = sessionFactory.openSession();
User user = session.load(User.class, 1L); // returns proxy
System.out.println(user.getUsername()); // triggers DB fetch
session.close();
🔹 Key differences:
Method | Behavior | Null handling |
---|---|---|
get() | Eager: hits DB or cache immediately | Returns null if not found |
load() | Lazy: returns proxy | Throws ObjectNotFoundException if entity missing |
🔹 Important note:
✅ Both methods return an object in persistent state if found.
✅ Using get()
is safer and more common in CRUD apps.
✅ Using load()
can be efficient for lazy loading, but be careful about exceptions if the entity doesn’t exist.
✅ Key takeaway:
Use session.get(Entity.class, id)
to eagerly fetch an object by its primary key, or session.load()
for lazy-loading a proxy when you know the entity must exist.