java Hibernate 中的 query.uniqueResult() 和 session.load() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41546166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between query.uniqueResult() vs session.load() in Hibernate?
提问by Mohammad Mirzaeyan
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?
第一个方法是否返回代理对象?如果我再次调用它是否会访问数据库?
回答by Maximiliano De Lorenzo
There are some differences (as of Hibernate5.2.6).
有一些差异(从Hibernate5.2.6 开始)。
session.load()
session.load()
- It only searchs by id assuming that the Entity exists
- It will ALWAYS return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxyis an object with the given identifier value, its properties are not initializedyet, it just looks like a temporary fake object.
- Use this only to retrieve an instance that you assume exists, where non-existence would be an ObjectNotFoundException.
- 假设实体存在,它仅按 id 搜索
- 它总是会返回一个“代理”(休眠术语)而不会访问数据库。在 Hibernate 中,proxy是一个具有给定标识符值的对象,它的属性还没有初始化,它看起来就像一个临时的假对象。
- 仅使用它来检索您假设存在的实例,其中不存在将是ObjectNotFoundException。
query.uniqueResult()
query.uniqueResult()
- You can query with complex conditions, not only by the id
- Convenience method to return a single instance that matches the query, or
null
if the query returns no results. - It will return an entity with its collection initializedor not depending on the FetchType.
- 您可以使用复杂的条件进行查询,而不仅仅是通过 id
- 返回与查询匹配的单个实例的便捷方法,或者
null
如果查询没有返回结果。 - 它将返回一个实体,其集合是否已初始化,具体取决于FetchType。