在Hibernate中通过ID获取对象 [英] Get object by ID in Hibernate
本文介绍了在Hibernate中通过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);
返回来源;
}
这段代码的好处是什么?
为什么不简单地写
$ p $ return $(getSession)getSession() .get(Source.class,id);
解决方案
这两段代码并不相同。
session.load(Source.class,id);
如果没有则会抛出异常来源
标识符 id
的实体。
getSession()。get(Source.class,id);如果没有来源,
会返回null 标识符 id
的实体。
I noticed that our senior developer uses following code for retrieving entity by 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);
解决方案
Those 2 pieces of code aren't equivalent.
session.load(Source.class, id);
will throw an exception if there is no Source
entity with the identifier id
.
getSession().get(Source.class, id);
will return null if there is no Source
entity with the identifier id
.
这篇关于在Hibernate中通过ID获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文