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);
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.
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.
In case of get() method, we will get the return value as NULL if the identifier is absent.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With