简体   繁体   中英

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

谁能告诉我load()get()在 Hibernate 中的优势是什么?

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); }
Whats the advantage of load() vs get() in Hibernate?
load() get()
Only use load() method if you are sure that the object exists. If you are not sure that the object exist, then use one of get() methods.
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.
在此处输入图片说明

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

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, t he 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.

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

load will return a proxy object.

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

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

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

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. eg

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. eg

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM