1. 乐观锁mybatis插件 配置
@Configuration
public class DataSourceConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
2. 实体类中注解 @Version 库里也需要有version字段
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_monitor_point_info")
public class MonitorPointInfo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
@Version
private Integer version;
3.直接调用更新方法自动更新version 字段
@Override
public boolean update(MonitorPointParam param) {
MonitorPoint bean = super.getById(param.getId());
bean.setMonitorPointNum(param.getMonitorPointNum());
return super.updateById(tempUpdate);
}
4. 查看乐观锁拦截
注意: 会先获取实体中version的值, 判断是否为空, 所以 version 默认需要给个值, 不能为 ‘null’
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement)args[0];
if (SqlCommandType.UPDATE != ms.getSqlCommandType()) {
return invocation.proceed();
} else {
Object param = args[1];
if (param instanceof Map) {
Map map = (Map)param;
Object et = map.getOrDefault("et", (Object)null);
if (et != null) {
String methodId = ms.getId();
String methodName = methodId.substring(methodId.lastIndexOf(".") + 1);
TableInfo tableInfo = TableInfoHelper.getTableInfo(et.getClass());
if (tableInfo != null && tableInfo.isWithVersion()) {
TableFieldInfo fieldInfo = tableInfo.getVersionFieldInfo();
Field versionField = fieldInfo.getField();
-----------------
Object originalVersionVal = versionField.get(et);
if (originalVersionVal == null) {
return invocation.proceed();
}
String versionColumn = fieldInfo.getColumn();
Object updatedVersionVal = this.getUpdatedVersionVal(fieldInfo.getPropertyType(), originalVersionVal);
if ("update".equals(methodName)) {
AbstractWrapper<?, ?, ?> aw = (AbstractWrapper)map.getOrDefault("ew", (Object)null);
if (aw == null) {
UpdateWrapper<?> uw = new UpdateWrapper();
uw.eq(versionColumn, originalVersionVal);
map.put("ew", uw);
} else {
aw.apply(versionColumn + " = {0}", new Object[]{originalVersionVal});
}
} else {
map.put("MP_OPTLOCK_VERSION_ORIGINAL", originalVersionVal);
}
versionField.set(et, updatedVersionVal);
return invocation.proceed();
}
return invocation.proceed();
}
}
return invocation.proceed();
}
}