Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Hibernate cache

I have the following code:

Person a = new Person();
a.setName("John");

Session session = openHibernateSession();

session.beginTransaction();

session.saveOrUpdate(a);

Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();

...

session.commit();

What I want is to have the ability to search objects from both the database and Hibernate's cache. The following example returns null upon calling uniqueResult. Is there any way to retrieve saved objects that have not yet been committed to the database?

like image 232
user1544745 Avatar asked Feb 25 '13 12:02

user1544745


1 Answers

If you are searching other than ID then Hibernate will not use first level cache. Hibernate get and load is related to first level cache by default but criteria query is not. In your case there are two solution from my side

  1. By flushing session = Just flush your session like this session.flush(); while doing so data from session will be synchronize to database hence Id will ge generated and as result Criteria query will find the result in database and will result list to you.

  2. Enable hibernate second level cache = You can enable second level cache by hibernate cache providers like ehCache and apply the trick.

like image 130
Rais Alam Avatar answered Sep 19 '22 11:09

Rais Alam