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?
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.
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.
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.
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.
There are some differences (as of Hibernate 5.2.6).
session.load()
query.uniqueResult()
null
if the query returns no results.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With