user1544745
user1544745

Reputation: 697

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?

Upvotes: 7

Views: 484

Answers (5)

Amby
Amby

Reputation: 462

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

Upvotes: 0

Mark Harris
Mark Harris

Reputation: 3

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.

Upvotes: 0

JcLucky
JcLucky

Reputation: 1

session.beginTransaction();

session.saveOrUpdate(a);

session.flush();

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

Upvotes: 0

Grim
Grim

Reputation: 1974

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!

Upvotes: 0

Rais Alam
Rais Alam

Reputation: 7016

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.

Upvotes: 1

Related Questions