✅ Short Answer
No — Hibernate’s natural ID API (session.byNaturalId(...)
) is designed for one entity lookup at a time.
It doesn’t support batch fetching multiple different natural IDs in a single call.
🔎 Detailed Explanation
🔹 How natural ID API works
- It’s built to fetch one entity by one unique natural ID value:
User user = session.byNaturalId(User.class)
.using("email", "alice@example.com")
.load();
There is no session.byNaturalId(...).using(...).loadMany(...)
API.
🔹 What about multiple emails?
If you have 10 emails and want 10 matching entities:
✅ You must either:
- Issue 10 separate natural ID lookups in a loop (inefficient for large batches), or
- Use a JPQL IN query, which is the recommended way.
🔹 Example with JPQL IN clause
List<String> emails = List.of("a@example.com", "b@example.com", "c@example.com");
List<User> users = em.createQuery(
"SELECT u FROM User u WHERE u.email IN :emails", User.class)
.setParameter("emails", emails)
.getResultList();
✅ This retrieves all matching users in one database round trip, which is much more efficient than multiple natural ID loads.
🔹 Important note
Natural ID caching also won’t help you batch — it’s per single natural ID lookup.
📌 Key Takeaways
✅ Natural ID API (byNaturalId()
) only supports one lookup at a time.
✅ To retrieve multiple entities by their natural IDs, use a JPQL IN query instead.
✅ That way, you get all matches in one query, avoiding N+1 lookups.