javahibernatecachingormnatural-key

What's the advantage of finding an entity using the Hibernate @NaturalId


Is there any advantage to find an object using the Hibernate's @NaturalId?

I'm concerned about the fact that Hibernate performs two queries to get an object using @NaturalId. The first query just to get the id and the second query to load the real object.


Solution

  • The major advantage is that you can use the Cache to resolve the entity without hitting the database.

    When the ResolveNaturalIdEvent event is thrown, Hibernate will try to:

    So, it's the same benefit as with using the entity loading through the Persistence Context API (e.g. EntityManager.find()).

    The only time when two queries are executed is when the entity is not already cached (1st or 2nd level cache).