使用Hibernate @NaturalId查找实体的好处是什么 [英] What's the advantage of finding an entity using the Hibernate @NaturalId
问题描述
使用Hibernate的@NaturalId查找对象是否有优势?
Is there any advantage to find an object using the Hibernate's @NaturalId?
我担心Hibernate执行两个查询以使用@NaturalId获取对象. 第一个查询仅用于获取ID,第二个查询用于加载真实对象.
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.
推荐答案
As I explained in this article, the major advantage is that you can use the Cache to resolve the entity without hitting the database.
ResolveNaturalIdEvent 引发事件,Hibernate将尝试:
When the ResolveNaturalIdEvent event is thrown, Hibernate will try to:
- 从一级缓存中加载关联的实体ID
- 从二级缓存中加载关联的实体ID(如果已启用)
-
如果一级缓存不能满足我们的要求,则回退到数据库查询
- 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).
这篇关于使用Hibernate @NaturalId查找实体的好处是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!