Can anyone tell me what's the advantage of load()
vs get()
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.
get() It will always return null , if the identity value is not found in database.
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.
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.
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); }
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