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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.