基于Mybatis
1:数据库添加version字段
2:Java实体类对应字段添加==@Version注解==,将版本交由mybatis自动管理
@Data
@ToString
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false) //不继承equals和hashcode方法
@TableName("taskinfo_logs")
public class TaskInfoLogsEntity extends TaskInfoEntity{
@Version //版本号,用乐观锁
private Integer version;
@TableField
private Integer status;
}
3:添加乐观锁拦截器Bean(完成)
@SpringBootApplication
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class,args);
}
//乐观锁拦截器
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
测试:
注意:乐观锁字段的值首次添加要初始化
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ScheduleApplication.class)
public class TaskInfoLogsMapperTest {
@Autowired
private TaskInfoLogsMapper logsMapper;
@Test
public void test(){
TaskInfoLogsEntity logsEntity = new TaskInfoLogsEntity();
logsEntity.setTaskType(2000);
logsEntity.setExecuteTime(new Date());
logsEntity.setPriority(100);
logsEntity.setParameters("logs".getBytes());
logsEntity.setVersion(1); //首次必须初始化版本号!!
logsEntity.setStatus(0);
logsMapper.insert(logsEntity);
TaskInfoLogsEntity entity = logsMapper.selectById(logsEntity.getTaskId());
System.out.println("保存后得到的日志对象:"+entity);
entity.setPriority(3);
logsMapper.updateById(entity);
TaskInfoLogsEntity byId = logsMapper.selectById(entity.getTaskId());
System.out.println("第一次修改后查询得到的日志对象:"+byId);
entity.setPriority(5);
logsMapper.updateById(entity);
byId = logsMapper.selectById(entity.getTaskId());
System.out.println("第二次修改后查询得到的日志对象:"+byId);
}
}
数据库: