10

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Mohammad Mirzaeyan
  • 845
  • 3
  • 11
  • 30
  • Possible duplicate of [Whats the advantage of load() vs get() in Hibernate?](http://stackoverflow.com/questions/5370482/whats-the-advantage-of-load-vs-get-in-hibernate) – Azodious Jan 09 '17 at 10:49
  • It's not exact duplicate, but accepted answer answers your question too. – Azodious Jan 09 '17 at 10:50
  • @Azodious it's not about query.uniqueResualt() it's about session.get() i think they have different behavior – Mohammad Mirzaeyan Jan 09 '17 at 11:35
  • doesn't explanation of `load` in that question answer your question? `uniqueResult` can return `null` but `load` will never. – Azodious Jan 09 '17 at 13:13

1 Answers1

11

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.
informatik01
  • 16,038
  • 10
  • 74
  • 104
  • does query.uniqueResult() return a proxy object ? if i call it for secound time for same query it will hit the database ? – Mohammad Mirzaeyan Jan 10 '17 at 08:15
  • It will hit the database or not depending on the cache configuration, you can configure second level cache for the entire class or only for some attributes. I am not sure about the proxy object, in my understunding query.uniqueResult() will return a proxy object if FetchType is lazy. – Maximiliano De Lorenzo Jan 10 '17 at 12:04
  • https://docs.jboss.org/hibernate/orm/current/javadocs/org/hibernate/Session.html#load-java.lang.Class-java.io.Serializable- it could be persistent instance or proxy. not always proxy – Bilbo Baggins Jun 01 '17 at 10:44