开发者

Concurrency issue in JPA and JTA [duplicate]

This question already has answers here: Closed 12 years ago.

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
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜