8

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);
DataNucleus
  • 15,497
  • 3
  • 32
  • 37
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • 1
    I guess this was developed with older hibernate version. I think hibernate 3.4 onwards supports getSession(). – kosa Oct 30 '13 at 17:52
  • Maybe he also wanted to keep the code "clean" according to the book "Clean Code" by Robert C. Martin instead of writing more than one statement on one line of code. – L.Butz Oct 30 '13 at 18:04

1 Answers1

11

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.

ben75
  • 29,217
  • 10
  • 88
  • 134