Difference between load( ) vs get( ) in Hibernate
The following Hibernate code snippet retrieves a User object from the database:
load()
--------------
1). Only use the
2).
3).
get( )
---------
1). If you are not sure that the object exists, then use one of the
2).
3).
For References:
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 }
For References: