Java 在 Hibernate 中通过 ID 获取对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19690225/
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
Get object by ID in Hibernate
提问by MyTitle
I noticed that our senior developer uses following code for retrieving entity by ID:
我注意到我们的高级开发人员使用以下代码通过 ID 检索实体:
@Override
public Source get(Long id) {
Session session = getSession();
if( session == null )
session = sessionFactory.openSession();
final Source source = (Source)session.load(Source.class, id);
Hibernate.initialize(source);
return source;
}
What is benefit of this code?
这段代码有什么好处?
Why not simply writing
为什么不简单地写
return (Soruce) getSession().get(Source.class, id);
回答by ben75
Those 2 pieces of code aren't equivalent.
这两段代码是不等价的。
session.load(Source.class, id);
will throw an exceptionif there is no Source
entity with the identifier id
.
如果没有带有标识符的实体,将抛出异常。Source
id
getSession().get(Source.class, id);
will return nullif there is no Source
entity with the identifier id
.
如果没有带有标识符的实体,则返回 null。Source
id