I try to write blogs whenever I get spare time

Just to let you know what I am trying to learn and what I am doing now.

The problem with the external update in Database of a Java EE project and how to overcome it.

Suppose you are developing a java EE project and you need some sort of trigger or procedure to do some back-end works like generating any customized serial number for table entries. You have written that trigger or procedure for the underlying database and then, you have made it to run in the back-end. Ok, you have done the right thing, everything is going right. But oops, are you facing any weired problem when reading back the data in your front-end application? Is there inconsistencies between the actual data and the data in the DB? Yes, you'll face this inconsistency.
The actual problem is that, when you read data through your session beans, all the JPQL queries are made to the EJBs, not to the actual DB. The EJBs themselves cache DB data and they only reflects changes made through the session beans (i.e. through the container). When you write a row in any database table via session beans and after that your trigger changes or inserts any data to that row, EJB can only know about the insert operation done by the session bean, it doesn't know any external change done by your trigger. That's why, when you read back that row by your session bean, you'll get the data excluding the change made by the trigger.
To overcome this issue, you can take either of the following ways:

  • You can use native query in your read operation of the session bean. For an example, you can use "entityManager.createNativeQuery("some query");" . Where, entityManger is the instance of the EntityManager class and "some query" means any raw query for your underlying database.
  • You can use use the default JPQL queries but after getting the list of data (object list of some entity) from that query, refresh all the entity objects. For an example:
personList = entityManager.createQuery(some JPQL query).getResultset();
for (Person person : personList)
{
entityManager.refresh(person);
}
And now look at the read data again. Is the inconsistency disappeared now? Yes, you have solved the problem successfully. :-)

2 comments:

Unknown said...

Hillol, thanks for the nice post.
I have solved the problem in another way.
After create or update an object through session bean i have called the refresh method for that object. For an example:

em.persist(person);
em.refresh(person);

Hillol said...

Thanks Zawoad, for the solution you have given.

Post a Comment