Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between query.uniqueResult() vs session.load() in Hibernate?

Tags:

java

hibernate

Can anyone tell me what's the difference between this code:

// This following method checks if there is an open session
// and if yes - returns it,  if not - opens a new session. 
Session session = getSession();
Query query = session.createQuery("from Entity e where e.id = 1");
Entity object = (Entity)query.uniqueResult(); 

and this:

 Session session = getSession();
 Entity object = (Entity)session.load(Entity.class, new Integer(1));


Does the first method return a proxy object? And if I call it again does it hit the database?

like image 519
Mohammad Mirzaeyan Avatar asked Jan 09 '17 10:01

Mohammad Mirzaeyan


People also ask

What is query uniqueResult () in Hibernate?

query.uniqueResult() You can query with complex conditions, not only by the id. Convenience method to return a single instance that matches the query, or null if the query returns no results.

What is the difference between Get () and load () method of Session object in Hibernate?

From the output it's clear that 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.

What is the difference between query and criteria in Hibernate?

HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.

Which is Better get or load in Hibernate?

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.


1 Answers

There are some differences (as of Hibernate 5.2.6).

session.load()

  • It only searchs by id assuming that the Entity exists
  • It will ALWAYS return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just looks like a temporary fake object.
  • Use this only to retrieve an instance that you assume exists, where non-existence would be an ObjectNotFoundException.


query.uniqueResult()

  • You can query with complex conditions, not only by the id
  • Convenience method to return a single instance that matches the query, or null if the query returns no results.
  • It will return an entity with its collection initialized or not depending on the FetchType.
like image 75
Maximiliano De Lorenzo Avatar answered Oct 18 '22 18:10

Maximiliano De Lorenzo