Anthony
Anthony

Reputation: 12736

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

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

Upvotes: 79

Views: 82344

Answers (11)

Premraj
Premraj

Reputation: 74641

Whats the advantage of load() vs get() in Hibernate?
load() get()
Only use load() method if you are sure that the object exists. It is used for LAZY loading of entities. If you are not sure that the object exist, then use one of get() methods.It is used for immediate loading of entities.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won't be hit until the proxy is first invoked. get() will hit the database immediately.

source

Proxy means, hibernate will prepare some fake object with given identifier value in the memory without hitting a database.
enter image description here

For Example:
If we call session.load(Student.class,new Integer(107));

hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized.

Source

Upvotes: 71

Bharat Shah
Bharat Shah

Reputation: 1

Both load() and get() methods are used to retrieve an object from the database in Hibernate. However, there are some key differences between the two methods:

Object Initialization: The load() method returns a proxy object that is lazily initialized, meaning that it doesn't actually fetch data from the database until the object is first accessed. On the other hand, the get() method fetches the data from the database immediately and returns the fully initialized object.

Exception Handling: If the load() method is called for a non-existent object, Hibernate will throw an ObjectNotFoundException when the proxy is accessed. In contrast, if the get() method is called for a non-existent object, it will return null.

Database Hit: If you call load() method, it hits the database immediately only if you access some other property or method of the returned object. But if you call get() method, it hits the database immediately and returns the complete object, which can be accessed by any of its properties or methods.

Performance: The load() method can improve performance because it doesn't hit the database immediately, and therefore can reduce the number of queries sent to the database. This can be useful in cases where you need to retrieve a large number of objects. However, if you are certain that the object you are retrieving exists in the database, the get() method can be faster because it fetches the data immediately and avoids the overhead of proxy creation and initialization.

In summary, the main advantage of load() is its lazy initialization, which can help to reduce database hits and improve performance in certain situations. However, it is important to be aware of the potential for ObjectNotFoundException errors when using load(). On the other hand, the get() method is more straightforward and can be faster in cases where you need to fetch the object immediately and don't want to deal with proxy initialization or exceptions.

You can find more about hibernate here.

Upvotes: 0

Vikki
Vikki

Reputation: 2025

Get() returns the object by fetching it from database or from hibernate cache whereas load() just returns the reference of an object that might not actually exists, it loads the data from database or cache only when you access other properties of the object.

With load(), we are able to print the id but as soon as we try to access other fields, it fires database query and throws org.hibernate.ObjectNotFoundException if there is no record found with the given identifier. It’s hibernate specific Runtime Exception, so we don’t need to catch it explicitly.

Upvotes: 1

Govind Sudumbrekar
Govind Sudumbrekar

Reputation: 11

session.load(): It will always return a proxy object with the given identity value, even the identity value is not exists in database. However, when you try to initialize a proxy by retrieve it’s properties from database, it will hit the database with select statement. If no row is found, a ObjectNotFoundException will throw.

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

Upvotes: 1

David Pham
David Pham

Reputation: 1803

The performance issues is also major difference between get and load method.

The get() method fetches data as soon as it’s executed while the load() method returns a proxy object and fetches only data when object properties is required. So that the load() method gets better performance because it support lazy loading. Whe should use the load() method only when we know data exists because it throws exception when data is not found. In case we want to make sure data exists we should use the get() method.

In short, you should understand the differential in between, and decide which method is best fix in your application.

I found this differences on the tutorial Difference between get and load method in Hibernate

Upvotes: 5

Dmitry Sobolev
Dmitry Sobolev

Reputation: 947

From the "Java Persistence with Hibernate" book, page 405:

The one difference between get() and load() is how they indicate that the instance could not be found. If no row with the given identifier value exists in the database, get() returns null. The load() method throws an ObjectNotFoundException. It’s your choice what error-handling you prefer.

More important, the load() method may return a proxy, a placeholder, without hitting the database. A consequence of this is that you may get an ObjectNotFoundException later, as soon as you try to access the returned placeholder and force its initialization (this is also called lazy loading; we discuss load optimization in later chapters.) The load() method always tries to return a proxy, and only returns an initialized object instance if it’s already managed by the current persistence context. In the example shown earlier, no database hit occurs at all! The get() method on the other hand never returns a proxy, it always hits the database.

You may ask why this option is useful—after all, you retrieve an object to access it. It’s common to obtain a persistent instance to assign it as a reference to another instance. For example, imagine that you need the item only for a single purpose: to set an association with a Comment: aComment.setForAuction(item). If this is all you plan to do with the item, a proxy will do fine; there is no need to hit the database. In other words, when the Comment is saved, you need the foreign key value of an item inserted into the COMMENT table. The proxy of an Item provides just that: an identifier value wrapped in a placeholder that looks like the real thing.

Upvotes: 40

Satya
Satya

Reputation: 8346

  • 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:

Ex: if you are trying to load /get Empoyee object where empid=20. But assume record is not available in DB.

 Employee employee1 = session.load(Employee.class,20);  //Step-1
 system.out.println(employee1.getEmployeeId();       //Step-2  --o/p=20
 system.out.println(employee1.getEmployeeName();       //Step-3 -->O/P:ObjectNotFoundException

If you use load in step-1 hibernate wont fire any select query to fetch employee record from DB at this moment.At this pint hibernate gives a dummy object ( Proxy ). This dummy object doesnt contain anything. it is new Employee(20). you can verify this in step-2 it will print 20. but in step-3 we are trying to find employee information. so at this time hibernate fires a sql query to fetch Empoyee objct. If it is not found in DB.throws ObjectNotFoundException.

Employee employee2 = session.get(Employee.class,20);  //Step-4

for session.get() hibernate fires a sql query to fetch the data from db. so in our case id=20 not exists in DB. so it will return null.

Upvotes: 7

Kaushik Lele
Kaushik Lele

Reputation: 6637

When Load is called it returns a Proxy object. Actual select query is still not fired. When we use any of the mapped property for the first time the actual query is fired. If row does not exist in DB it will throw exception. e.g.

Software sw = ( Software )session.load(Software.class, 12);

Here sw is of proxy type. And select query is not yet called. in Eclipse debugger you may see it like

sw Software$$EnhancerByCGLIB$$baf24ae0  (id=17) 
   CGLIB$BOUND         true 
   CGLIB$CALLBACK_0 CGLIBLazyInitializer  (id=23)   
   CGLIB$CALLBACK_1 null    
   CGLIB$CONSTRUCTED    true    
   id                  null 
   prop1               null 
   softwareprop        null 

when I use

 sw.getProp1()

the select query is fired. And now proxy now knows values for all the mapped properties.

Where as when get is called, select query is fired immediately. The returned object is not proxy but of actual class. e.g.

Software sw = ( Software )session.get(Software.class, 12);

Here sw is of type Software itself. If row exists then all mapped properties are populated with the values in DB. If row does not exist then sw will be null.

sw  Software  (id=17)   
id  Integer  (id=20)    
prop1   "prodjlt1" (id=23)  
softwareprop    "softwrjlt1" (id=27)    

So as always said, use load only if you are sure that record does exist in DB. In that case it is harmless to work with the proxy and will be helpful delaying DB query till the mapped property is actually needed.

Upvotes: 4

axtavt
axtavt

Reputation: 242766

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);
    }
    

Upvotes: 85

GuruKulki
GuruKulki

Reputation: 26428

load will return a proxy object.

get will return a actual object, and returns null if it wont find any object.

Upvotes: 6

Anthony
Anthony

Reputation: 12736

A: This is explained in the hibernate reference. One difference was performance and the other one is that load throws an unrecoverable Exception when no Object is found for the ID.

More details here

Upvotes: 4

Related Questions