使用Hibernate的@NaturalId查找对象的好处 [英] Advantage of find an object using Hibernate's @NaturalId

查看:1018
本文介绍了使用Hibernate的@NaturalId查找对象的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Hibernate的@NaturalId来查找对象是否有优势?



我担心Hibernate执行两个查询来获取使用@ NaturalId。 第一个查询仅用于获取id,第二个查询用于加载实际对象。



预先感谢。

解决方案

正如我在的主要优点是你可以使用缓存来解析实体而不需要访问数据库。



ResolveNaturalIdEvent 事件被抛出,Hibernate会尝试:


  • 从第一级加载关联的实体ID缓存

  • 从第二级缓存中加载关联的实体标识(如果启用)
  • 回退到数据库查询级高速缓存无法满足我们的要求

     可序列化的entityId = resolve FromCache(事件); 
    if(entityId!= null){
    if(traceEnabled)
    LOG.tracev(缓存中的已解决对象:{0},
    MessageHelper.infoString(persister,event .getNaturalIdValues(),event.getSession()。getFactory()));
    返回entityId;
    }

    return loadFromDatasource(event);




所以,和使用通过持久化上下文API加载的实体(例如 EntityManager.find())。



执行两个查询的唯一时间是实体尚未被缓存(第一级或第二级缓存)。


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.

Thanks in advance.

解决方案

As I explained in this article, 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).

这篇关于使用Hibernate的@NaturalId查找对象的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆