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?

0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

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();

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.