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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:25:08  来源:igfitidea点击:

Get object by ID in Hibernate

javahibernateorm

提问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 Sourceentity with the identifier id.

如果没有带有标识符的实体,将抛出异常Sourceid

getSession().get(Source.class, id);

will return nullif there is no Sourceentity with the identifier id.

如果没有带有标识符的实体,则返回 nullSourceid