简体   繁体   中英

How to use first level cache using criteria or query ? (Hibernate)

I have a one table (User) that contains many column,username is one of the column from them. This username column contains user name value like 'Sachin', 'Sameer', 'Krunal' etc..

My question is below: I am using autoComplete for search user name in username column from User table. When i write 'S' in autoComplete, my result should be in List and this List contain 'Sachin' and 'Sameer' username and want to store in cache and when i write again 'S' in autocomplete so i want to get result from cache and doesn't want to call same query to get data from User table. I am using criteria also using hql but don't get result from cache.

So How can i get this result?

Please guide me

First level cache is enabled by default in Hibernate. The scope of this cache is the session scope. When the session is closed, the associated cache is cleaned. The first time you request an entity in the session, the Hibernate will query the database. If you request it again into tho same session the Hibernate will get it from first level cache.

In your case you need the second level cache and query cache. In the second level cache the entities live beyond the session scope. So even after close the session, the cache keeps the entities. In the query cache the entities PKs are stored beyond the session scope too.

The query cache will return the PKs that are used to get the entities from the second level cache.

In your use case, You Can not use first level cache using criteria or query.

The Context of First Level Cache:

Whenever we do insert\\update\\delete\\ select by pk operations, then corresponding persistence objects will get placed automatically in session cache.

operation:

session.save()

session.update()

session.delete()

session.load()

Also In the context of Second level Cache :

Whenever we execute the hibernate queries like HQL,QBC,Select *.. statement, then all the records returned by select statement will be placed in Query Cache .

So good to enable Second level Cache.

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