Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of load() vs get() in Hibernate?

Tags:

java

hibernate

Can anyone tell me what's the advantage of load() vs get() in Hibernate?

like image 752
Antonio Avatar asked Mar 20 '11 18:03

Antonio


People also ask

How load method works in hibernate?

When ever the load() method is called, the hibernate creates a proxy object of a POJO class (provided as parameter), and it will set the id to the proxy object, then it returns the proxy object to the program.

What is the default return type of Session get () method?

get() It will always return null , if the identity value is not found in database.

Which is the right way to use Session get () method?

get() returns the object by fetching it from database or from hibernate cache. when we use get() to retrieve data that doesn't exists, it returns null, because it try to load the data as soon as it's called. We should use get() when we want to make sure data exists in the database.

Which two methods are used for retrieval by identifier in hibernate?

The get() method is very much similar to load() method. The get() methods take an identifier, and either an entity name or a class types.


1 Answers

Explanation of semantics of these methods doesn't explain the practical difference between them. Practical rule is the following:

  • Use get() when you want to load an object

  • Use load() when you need to obtain a reference to the object without issuing extra SQL queries, for example, to create a relationship with another object:

    public void savePost(long authorId, String text) {     Post p = new Post();     p.setText(text);      // No SELECT query here.      // Existence of Author is ensured by foreign key constraint on Post.     p.setAuthor(s.load(Author.class, authorId));      s.save(p); } 
like image 171
axtavt Avatar answered Oct 24 '22 13:10

axtavt