Querying Hibernate cache
Asked Answered
G

5

7

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?

Gradualism answered 25/2, 2013 at 12:35 Comment(0)
U
1

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.

Urger answered 25/2, 2013 at 13:15 Comment(0)
M
0

You can use the StatelessSession but be warned: those entitys are not bound to any session and you will get Exceptions if you like to resolve relations or lazy fields!

Melchior answered 25/2, 2013 at 13:58 Comment(0)
D
0
session.beginTransaction();

session.saveOrUpdate(a);

session.flush();

Criteria critera = session.createCriteria(Person.class);
critera.add(Restrictions.eq("name","John"));
Person personFromCache = (Person) criteria.uniqueResult();
Dihydric answered 8/3, 2013 at 1:46 Comment(0)
U
0

We do some similar things except using TestNg test framework. Several of the answers discuss the session.flush() method call. This is correct. The call to flush tells Hibernate to do several things, including making sure that all database calls currently waiting in the queue get executed and cleared from the queue.

Untruthful answered 14/3, 2013 at 20:25 Comment(0)
R
0

It returns data even if you are selecting on the basis of username. It is not returning null.

Righthand answered 31/10, 2014 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.