Class cache is not used when receiving an object by criteria

I set the cache class in the nhibernate.cfg.xml file.

When I get my object by identifier, I do not see SQL queries after loading the object.

But when I get an object using criteria, there are always SQL queries ...

EDIT:

I think this answers my question:

http://www.javalobby.org/java/forums/t48846.html

Let's say that we wanted to search for records based on more complex queries directly by identifier, for example by name. In this case, Hibernate must still issue the SQL statement to get the basic dataset for the query. So for example this code:

Request request = session.createQuery ("from Person as p where p.firstName =?"); query.setString (0, "John"); List l = query.list (); ... will refer to one choice (provided that our associations have been cached).

select * from Person, where firstName = 'John' This single choice will then return "1" and then the cache will be used for all other searches. since we all cached. This required single select query cache comes.

+1
source share
1 answer

Not sure if your “editing” means you found all the answers. NHibernate breaks the caching mechanism into two areas.

The first is a cache class, as described above. Any request for an object with a specific identifier (Session.Get (id) ;, reference property, collection) can be used by the class cache.

The second is the query cache. In this case, the key used for cache depends on the Criteria passed. They were used to get a set of results (where, order, top ...). In this case, cache is the set of identifiers returned by this request.

So, when the same criteria are applied, the cached set of identifiers is returned, and the cached objects from the class cache (by identifier) ​​are reused.

(The specific scenario is applicable to projection, which can also be cached in recent versions of NHibernate. In this case, the results do not contain an object with a unique identifier, but a set of columns. Although they are not suitable for identifier-based caching, it works as well. Version 3.3 does this for me)

So, to finally answer:

But when I get an object using criteria, there are always SQL queries ...

we must also enable the query cache:

 <property name="cache.use_second_level_cache">true</property> <property name="cache.use_query_cache">true</property> 

A second level cache is allowed, and objects with an identifier can be saved. Support for the query cache is also supported, so the second call to the same combination of criteria should not go to the SQL server at all.

Caching an example request:

 criteria.SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("LongTerm"); 
+2
source

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


All Articles