views:

457

answers:

2

I have a struts application that uses Hibernate to access a MYSQL DB. I have a number of pages that make changes to the DB. These changes go through fine, data is update in the DB. However when browsing to the page that should show this updated information its often not there, and even after a few page refreshes it still isn't there. Eventually it will turn up. I'm assuming this has something to do with hibernate caching data, but how can I ensure that data is up to date? I had assumed that as it all went through the hibernate session it would pick up changes? The code i'm using to do the update is :

    hSession = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = hSession.getTransaction();
    tx.begin();
    hSession.update(user) ;

Then to pull that user out again:

org.hibernate.Session hSession = HibernateUtil.getSessionFactory()
.getCurrentSession();
 Transaction tx = hSession.beginTransaction();
 User u= (User) hSession.load(User.class, userID);
+1  A: 

It is probably a result of the second level (session factory) hibernate cache.

Caching should be transparent and work fine with the code you gave, but problems occur usually when:

  1. You are running a cluster of machines and do not have a way for the caches to invalidate each other configured
  2. You are updating the database outside of hibernate.

The easiest way to determine if it is a second-level cache problem is to completely disable the cache in your hibernate config. If it is the cache, you can configure a cluster to know about each other so they can manage the cache automatically, or if it is a problem with outside-hibernate updates you can manually invalidate cache items with the hibernate api

Nathan Voxland
This is a single machine (just dev machine), and the only changes are made in hibernate, but I'll give disabling the cache a go and see what happens!
Sam Cogan
With a single machine you may still see 2nd level cache problems if you have multiple SessionFactory objects created. Each session factory is independent and acts like they are on separate physical systems. You may have multiple ones if you have different web apps or if your code creates them.
Nathan Voxland
+3  A: 

Too little information to really give an answer. But some points to check:

  • You are using transactions. Are you properly committing them? Maybe at some point your code cannot see changes, because the are not yet commited (or because the reading code is in another transaction which uses previous state).

  • The cache might also be a problem. To check, you could explicitly flush the cache after each change to the DB (Session.flush()). This will probably degrade performance, but might help you narrow down the problem.

sleske
Yes, transaction needs to be explicitly commited in the above set-up.
javashlook