Hibernate : Difference between load( ) vs get( ) in hibernate

The following Hibernate code snippet retrieves a User object from the database:
load()
————–
1). Only use the load() method if you are sure that the object exists.
2). load() method will throw an exception if the unique id is not found in the database.
3). load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

Session session = << Get session from SessionFactory >>

Long itemId = << Get the item id from request >>

try{

Item item = session.load(Item.class, itemId);

Bid bid = new Bid();

bid.setItem(item);

session.saveOrUpdate(bid);

} catch(ObjectNotFoundException e) {

log.error("Bid placed for an unavailable item");

// Handle the error condition appropriately

}

get( )
———
1). If you are not sure that the object exists, then use one of the get() methods.
2). get() method will return null if the unique id is not found in the database.
3). get() will hit the database immediately. 

Session session = << Get session from SessionFactory >>

Long itemId = << Get the item id from request >>

Item item = (Item) session.get(Item.class, itemId);

if(item != null) {

Bid bid = new Bid();

bid.setItem(item);

session.saveOrUpdate(bid);

} else {

log.error("Bid placed for an unavailable item");

// Handle the error condition appropriately

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s