• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

load() vs get()

 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,

Other than the load () method throwing exception when the id is not found, what is the difference between using load () and get () methods to load entities from a database?
 
sharath kumar reddy karnati
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
load: will throw error in case id is not found.
get: will return 'null' when id is not found.

Mostly 'get' will be helpful, if we are not sure whether id is present or not.

Ex. Cat cat = session.get(Cat.class,CatId);
if (cat==null)
session.save(cat);

Bye,
Sharath.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One other big key is one is fully loaded and the other is lazy loaded and only fetch the actual data when you call a getter on the returned object. So if that is the case, that is also what explains why one throws an Exception and one doesn't

Since load has to fill the object with data in all mapped attributes, if the id is not found then it can't fill the object, and therefore is best to through an exception.

Now get creates a proxy object and will only have the id loaded, if the id is found, if it is not found, then the proxy object is just null.

Mark
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So get () is a lazy load. Am I right?
 
Putthibong Bongbong
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Session.load() --> lazy load with proxy object
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always get get and load mixed up with which is which.

From the load Javadocs

"You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error."

So it looks like get would be the proxy, because if you want just determine if an instance exists you probably would not need the entire record to fill with data. Hibernate can then just do a simpler query I guess.

Mark
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found this to be a good resource to discuss on load() and get() methods of the Session.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic