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

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


At least one advantage is you will benefit from first level cache. So for example if you load User by email ( which is naturalid), you will get only the primary key id from db, and the user object from first level cache if it is already there. So faster load time as less network data transfer.