Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object by ID in Hibernate

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);
like image 237
WelcomeTo Avatar asked Oct 30 '13 17:10

WelcomeTo


People also ask

Which method is used for retrieval by identifier in Hibernate?

In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given identifier whereas load() method throws object not found exception.

What is the difference between load () and get ()?

get() loads the data as soon as it's called whereas load() returns a proxy object and loads data only when it's actually required, so load() is better because it support lazy loading. Since load() throws exception when data is not found, we should use it only when we know data exists.

What is the return type of get () method in Session when the ID column is not primary key?

In case of get() method, we will get the return value as NULL if the identifier is absent.


1 Answers

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.

like image 132
ben75 Avatar answered Oct 26 '22 01:10

ben75