樂觀鎖插件
1) com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor 注冊樂觀鎖插件
2) 如果想實現如下需求: 當要更新一條記錄的時候,希望這條記錄沒有被別人更新,確保當前只有一個人在操作
3) 樂觀鎖的實現原理:
取出記錄時,獲取當前 version 2
更新時,帶上這個 version 2
執行更新時, set version = yourVersion+1 where version = yourVersion
如果 version 不對,就更新失敗
4) @Version 用於注解實體字段,必須要有,數據庫中也應有對應的字段
@RunWith(value = SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class LeGuanLock { @Autowired private EmployeeMapper mapper; @Test public void testName() throws Exception { /** * UPDATE tbl_employee SET last_name=?, gender=?, * age=?, version=? WHERE id=? and version=? */ //更新操作 假設這個實體類是我們要更新到數據庫的數據 Employee employee = new Employee(); employee.setId(4); employee.setLastName("樂觀鎖"); employee.setGender("1"); employee.setAge(29); /* * 添加@Version注解字段 * spring配置文件中注冊樂觀鎖插件 * 假如有人手速比我們快,先更新,這時version不是2了,假設是3 * 更新就會失敗 */ employee.setVersion(2); Integer r = mapper.updateById(employee); System.out.println(r); } }
實體類中
@Version private Integer version;