Does an HQL query always get into the database and get the results?

I experienced hibernation and situations when you should use Criteria vs HQL , and I understand that with Hibernate every time we query the database using either Criteria or HQL , in both cases hibernate will receive a result set and enter memory, and then when we call this query again, the data will be retrieved from memory and then delete this database, do I understand correctly?

Also, as you can see from the comments on the question mentioned below, it was suggested that Hibernate Criteria will receive data from the session, and that HQL will always get into the database and, thus, any number of multiple calls to the HQL query will go and hit the database data and if so, then HQL causes more problems than a solution.

Please report this as I am a bit confused about the situation.

Link to question

+6
source share
2 answers

It depends on what requests you make and your cache settings.

Hibernate has three types of caches: session cache, request cache, and second-level cache. The session cache is always on, and the other two can be disabled.

Usually, caching is not the basis for using the API criteria over HQL or vice versa. Basically these are just different interfaces, essentially the same thing.

See http://www.javalobby.org/java/forums/t48846.html and http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html

+7
source

Basically, if you generate queries, you will probably get to the database, an exception to this is if you cached the query and parameters.

Hibernation requests (whether you use criteria or HQL) will only return objects from the session cache (first level cache) if you get it using @Id.

To cache a request, you can use the following syntax:

 session.createQuery("from X as x").setCacheable(true); 

Edited for comments:

The request does not match the get request with @Id. To get an object by its @Id, you should write something like:

 Entity myEntity = sessionFactory.getCurrentSession().get(Entity.class, 1); 
+1
source

Source: https://habr.com/ru/post/906765/


All Articles