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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With