Eclipse or SUNrise...

Eclipse or SUNrise...
...JAVA for sure

Thursday, June 28, 2007

EJB cacheing old data from database

Lately, I was working with postgres 8.x database and EJB3.0 from JDK5. I had problem of refreshing data that was saved in the DB. From some reason the Enterprise Entity Beans had been cacheing the previous values from the tables. The issue happend when there was couple of opperations one after another using the modified data. All the updates on the tables were transactional so it shouldn't happen - in theory.

So, how to solve the problem? First I tried the flush() method from the EntityManager after the persist() method, but it didn't help (actualy I don't know where it could come in handy...), the one that helped was the refresh() method. It takes one parameter, an object - Entity Bean representing the record from the database and checks it's latest version.

The example code is simple (EJB3.0), please note that exception handling is primitive and for example purposes only:

@PersistenceContext private EntityManager manager;

//..

int id = 1;
Query q = manager.createQuery("SELECT OBJECT(o) FROM TestTableBean o WHERE o.id = :id");
q.setParameter("id", id);

try
{
TestTableBean testTableBean = (TestTableBean)q.getSingleResult();
}
catch (NoResultException nre)
{
testTableBean = null;
}
catch (Exception e)
{
testTableBean = null;
System.err.println("ERROR: " + e.toString() + ":");
e.printStackTrace();
}

if (testTableBean != null)
{
int cachedValue = testTableBean.getValue(); // old one
manager.refresh(testTableBean);
int goodValue = testTableBean.getValue(); // correct one
}


So, if you need the data to be 100% up to date - simply use the refresh() method. I can't tell you how much impacts it on the performance yet, but in my opinion it looks like a good solution.

If you have any comments - please share it, I'm open for discusion.

No comments: