Search code examples
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:

    • load the associated entity id from the 1st level cache

    • load the associated entity id from the 2nd level cache (if enabled)

    • fall-back to a database query if the 1st level cache can't satisfy our request

        Serializable entityId = resolveFromCache( event );
        if ( entityId != null ) {
            if ( traceEnabled )
                LOG.tracev( "Resolved object in cache: {0}",
                        MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) );
            return entityId;
        }
      
        return loadFromDatasource( event );
      

    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).