简体   繁体   English

在Hibernate中query.uniqueResult()和session.load()之间有什么区别?

[英]What's the difference between query.uniqueResult() vs session.load() in Hibernate?

Can anyone tell me what's the difference between this code: 谁能告诉我这段代码有什么区别:

// This following method checks if there is an open session
// and if yes - returns it,  if not - opens a new session. 
Session session = getSession();
Query query = session.createQuery("from Entity e where e.id = 1");
Entity object = (Entity)query.uniqueResult(); 

and this: 和这个:

 Session session = getSession();
 Entity object = (Entity)session.load(Entity.class, new Integer(1));


Does the first method return a proxy object? 第一个方法是否返回代理对象? And if I call it again does it hit the database? 如果我再次调用它,它会打到数据库吗?

There are some differences (as of Hibernate 5.2.6). 存在一些差异(从Hibernate 5.2.6开始)。

session.load()

  • It only searchs by id assuming that the Entity exists 它仅通过id搜索,假设实体存在
  • It will ALWAYS return a “ proxy ” (Hibernate term) without hitting the database. 它总是会返回一个“ 代理 ”(Hibernate术语)而不会访问数据库。 In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just looks like a temporary fake object. 在Hibernate中, proxy是一个具有给定标识符值的对象,它的属性尚未初始化 ,它看起来像一个临时假对象。
  • Use this only to retrieve an instance that you assume exists, where non-existence would be an ObjectNotFoundException . 仅用于检索您假定存在的实例,其中不存在将是ObjectNotFoundException


query.uniqueResult()

  • You can query with complex conditions, not only by the id 您可以使用复杂条件查询,而不仅仅是id
  • Convenience method to return a single instance that matches the query, or null if the query returns no results. 返回与查询匹配的单个实例的便捷方法,如果查询未返回结果,则返回null
  • It will return an entity with its collection initialized or not depending on the FetchType . 它将返回一个实体,其集合初始化或不取决于FetchType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM