Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 810
bruno.zambiazi Avatar asked Jan 27 '15 21:01

bruno.zambiazi


People also ask

What is @NaturalId in Hibernate?

Natural ids represent unique identifiers that naturally exist within your domain model. Even if a natural id does not make a good primary key, it still is useful to tell Hibernate about it.

What is a natural id number?

A natural identifier is something that is used in the real world as an identifier. An example is a social security number, or a passport number.

Which annotation is used to model a natural id such as the isbn of a Book?

The only thing you have to do to model an attribute is a natural id, is to add the @NaturalId annotation. You can see an example in the following code snippet. The isbn number of a Book is a typical natural id. It identifies the record but is more complex than the primary key id.


1 Answers

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

like image 97
Vlad Mihalcea Avatar answered Sep 21 '22 13:09

Vlad Mihalcea