简体   繁体   中英

What's the difference between query.uniqueResult() vs session.load() in 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?

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 .

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