tags:

views:

41

answers:

1

Possible Duplicate:
concurrency (stale data) problem in JPA

Sorry for duplicating, but I think I didn't get satisfactory answers so posting again Let's say I have methods with following signature

Object getData(int id) {  
  //create a entity manager
  //get data frm db
  //return data
}

updateData() {
  Object obj = getData(id) 
  //get entity manager
  //start transcation tx
  //update
  //commit tx
}

Now will it cause concurrency issue? Can data be stale in worst case? E.g. if I getData and by the time I update, if someone updates the data will my updateData will have stale data? Now can i use following:Will i solve the problem?

Object getData(int id,Entitymanager em) {  

      //get data frm db using em
      //return data
    }

 updateData() {
      Object obj = getData(id) 
      //get entity manager em
      //start transcation tx
      //getdata using getData(id,em)
      //commit tx
    }
A: 

If two separate requests access updateData() concurrently you may get stale data. You may handle the staleness by locking the fetched data in updateData(). If you're using Hibernate as your JPA provider you can lock the data as follows:

updateData() {
    Object obj = getData(id);
    Session session = (Session) em.getDelegate();
    session.refresh(obj, LockMode.UPGRADE);
}

The refresh is necessary because it may happen that between the fetching and the locking of the data another transaction completes in updateData.

Please keep in mind that the entity manager used in getData and updateData must be the same.

kraftan