当前使用版本(必填,否则不予处理)
3.5.2
该问题是如何引起的?(确定最新版也有问题再提!!!)
saveOrUpdate源码是判断id是否为空和根据id查询是否为空来确定是新增还是修改。在确定是执行update时,还是用的传入的entity执行的update,而不是用getById查询到的对象,导致version字段无法自增。
重现步骤(如果有就写完整)
在配置乐观锁的情况下,带id执行saveOrUpdate方法。
报错信息
无
Comment From: binfengyan
放在哪个update也不会先通过getById查询一遍
Comment From: romande
放在哪个update也不会先通过getById查询一遍
public boolean saveOrUpdate(T entity) {
if (null == entity) {
return false;
} else {
TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable)idVal)) ? this.updateById(entity) : this.save(entity);
}
}
看源码的话,最后return判断更新还是插入其实是通过this.getById去查了的,但是后面updateById传的实体是entity,这个写法会导致乐观锁无法生效,update的时候不会更新version,我是说的这个问题。
Comment From: romande
是否可以用getById查出的对象,然后copy entiy里的数据进行update,这样是不是version就可以起作用了。
Comment From: romande
放在哪个update也不会先通过getById查询一遍
我遇到的问题是,一定要先查询出这条数据,再更新,乐观锁才会生效。难道是需要另外做什么配置么?
Comment From: shuaizai88
比如新增用户user 1 version 1 张三和李四都进到了修改页面 他们前端拿到的数据version都是1 李四先点了修改 (version 2),张三应该是修改不成功的。 所以正确的玩法应该是 前端要把version 给后台传一下,按照上面先查询会导致张三李四 都修改成功,从业务上是不ok的。
Comment From: VampireAchao
这个是乐观锁的用法限制,需要在update时给定一下version,可以考虑将version查询时返回给前端,在触发更新的地方传过来version