When JPA is used by the persistence layer, an annotation @version is provided by default to enable optimistic locking
Simply put, a version field serves as an optimistic lock.
First, design the entity class.
/** * Created by Xujingfeng on 2017/1/30. */ @Entity @Table (name = "t_student") public class Student { @Id @GenericGenerator (name = " Pkuuid ", strategy = " Uuid2 ") @GeneratedValue (generator = "Pkuuid") @Column (length = 36) private String ID; @Version private int Version; private String name; //getter () ... //setter () ...}
DAO layer
/** * Created by xujingfeng on 2017/1/30. */public interface StudentDao extends JpaRepository<Student,String>{ @Query("update Student set name=?1 where id=?2") @Modifying @Transactional int updateNameById(String name,String id);}
The controller layer acts as a unit test by accessing a requestmapping to trigger the method we want to test.
/** * Created by Xujingfeng on 2017/1/30. */@ControllerPublicClassStudentcontroller {@Autowired Studentdao Studentdao;@RequestMapping ("Student.html")@ResponseBodyPublic StringStudent() {Student Student =New Student (); Student.setname ("Xujingfeng"); Studentdao.save (student);Return"Student"; }@RequestMapping ("Testversion.html")@ResponseBodyPublic StringTestversion()Throws Interruptedexception {Student Student = Studentdao.findone ("6ed16acc-61df-4a66-add9-d17c88b69755"); Student.setname ("Xuxuan");New Thread (New Runnable () {@OverridePublicvoidrun () {Studentdao.findone (1000); Studentdao.save (student); return "testversion";} @RequestMapping ( "updatenamebyid.html") @ResponseBody public String updatenamebyid () {Studentdao.updatenamebyid ( "xuxuan2", "6ed16acc-61df-4a66-add9-d17c88b69755"); return "Updatenamebyid";}}
Here are three methods, mainly the three points of attention we want to test.
The first method student.html we want to see how springdata grows with the version field. Do not map, directly to the conclusion, for the addition of @version annotations, we do not need to manually control, each save operation will be on the original basis +1, if the initial null, then springdata automatically set it to 0.
The second method testversion.html is the core of optimistic lock, when multiple threads concurrently access the same row of records, the addition of @version optimistic lock, the program will be how to control it?
or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.example.jpa.Student#6ed16acc-61df-4a66-add9-d17c88b69755]
Exception information such as above, the main thread and new threads get the same row record, and the new thread first commits the transaction, the version number is consistent, and the modification succeeds. Wait until the main thread and then want to save commit transaction, get a version number inconsistent exception, then in the project development should be caught in the exception of the business content to do the corresponding processing, is to retry or discard etc ...
The third method, updatenamebyid.html, is to emphasize that the update,delete operation in the @Query does not trigger the related agent operation of Springdata, but rather translates it into native SQL, so be aware of this when used in a project.
Summarize
Optimistic locking, used in some sensitive business data, and its own modification: optimistic, the meaning of the representative is that most of the scenarios are consistent version. But from the business point of view and ensure strict consistency of data, avoid dirty reading and other issues, the use of the scene needs to be considered. Remember the previous blog simple introduction of the concept of row-level lock, in fact, and optimistic lock is to want to the database level plus lock control concurrency, then when to use optimistic lock, row-level lock, when the program level with synchronization lock, but also according to the specific business scenarios to judge. Finding a solution that meets your project's needs and finding a balance of performance and reliability is the value of a programmer.
Source: http://www.importnew.com/26099.html
"Spring" 27, JPA implementation optimistic lock @version annotation use