Concurrency (obsolete data) in JPA

Say I have methods with the 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 this cause a concurrency problem? Can data be past due in the worst case? For instance. if I getData, and by the time of the update, if someone updates the data, updateDatawill my data be outdated? Now I can use the 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
    }
+3
source share
3 answers

Yes it can happen.

If you get an entity (version 1), someone else modifies it (creating version 2), then you change version 1 and save it, any changes in version 2 will be lost.

, concurrency, @Version . get update, . .

+5

updateData() , . , updateData(). Hibernate JPA, :

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

An update is necessary because it may happen that between the retrieval and locking of the data, another transaction completes at updateData.

Keep in mind that the object manager used in getDataand updateDatamust be the same.

0
source

Source: https://habr.com/ru/post/1770474/


All Articles