mybatis-plus加了@Version也无法使用乐观锁
//不要忘了在主程序入口加@Mapscan注解
@Configuration
public class OptimisticLocker {
@Bean
public OptimisticLockerInterceptor getOptimistic() {
return new OptimisticLockerInterceptor();
}
}
//你的entity实体类
@Data
@Accessors(chain = true)
@TableName("user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId("id")
private Long id;
@Version//必加
private Integer version;
}
如果有以上配置还是无法使用乐观锁,则是因为没有先查出要更新的对象,再更新。如下:
public ResultMap updateUserById(UserDto dto) {
**//先按照id查询要更新的对象**
User user = userMapper.selectById(dto.getId());
ResultMap<Object> map = new ResultMap<>();
int update=-1;
try {
**//再来更新对象**
update = userMapper.updateById(user);
}catch (Exception e){
log.error("更新失败{}",e.getCause());
}
if (update < 0) {
return map.setCode(InfoEnum.UPDATE_FAILED.getCode()).setMessage(InfoEnum.UPDATE_FAILED.getMessage());
} else {
return map.setCode(InfoEnum.UPDATE_SUCCESS.getCode()).setMessage(InfoEnum.UPDATE_SUCCESS.getMessage());
}
}
打印的SQL语句如下:
==> Preparing: UPDATE user SET version=?, name=?, age=?, email=? WHERE id=? AND version=?
==> Parameters: 4(Integer), test(String), 22(Integer), test@ggg.com(String), 2(Long), 3(Integer)
<== Updates: 1
==> Preparing: UPDATE user SET version=?, name=?, age=?, email=? WHERE id=? AND version=?
==> Parameters: 4(Integer), test(String), 22(Integer), test@ggg.com(String), 2(Long), 3(Integer)
<== Updates: 1