背景
很多朋友,想把新增和编辑做在一起。
没想到自己遇到坑了,
自己的saveOrUpdate的提交总是update。
控制台sql输出
UPDATE t_course_type SET course_type_name=?,
create_time=?,
create_user=?,
update_time=?,
update_user=?
报错
com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation
官方文档
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
分析
发现上面的sql没有where条件。
以为是新增操作,没有id,主键是自增的,就加了个判断
ObjectUtils.isNotEmpty(courseTypeId)。
发现是updateWrapper的eq方法 不能加condition参数。
错误方式
updateWrapper.eq(ObjectUtils.isNotEmpty(courseTypeId), CourseTypeEntity::getCourseTypeId, courseTypeId);
正确方式
去除第一个condition参数。保留2个参数即可。
updateWrapper.eq(CourseTypeEntity::getCourseTypeId, courseTypeId);
成功案例实现源码分享
LambdaUpdateWrapper<CourseTypeEntity> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(CourseTypeEntity::getCourseTypeId, courseTypeId);
CourseTypeEntity courseTypeEntity = new CourseTypeEntity();
if (courseTypeIdNotEmpty) {
courseTypeEntity.setCourseTypeId(courseTypeId)
.setUpdateTime(LocalDateTime.now())
.setUpdateUser(username)
.setCourseTypeName(courseTypeName)
.setCourseCount(courseCount);
} else {
courseTypeEntity.setCourseTypeName(courseTypeName)
.setCreateTime(LocalDateTime.now())
.setCreateUser(username)
.setUpdateTime(LocalDateTime.now())
.setUpdateUser(username);
}
boolean saveOrUpdate = this.saveOrUpdate(courseTypeEntity, updateWrapper);
总结
要去了解这个saveOrUpdate的源码的处理机制。
源码
default boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) {
return this.update(entity, updateWrapper) || this.saveOrUpdate(entity);
}
因为该方法默认是使用实体对象的id去匹配,
如果有就更新,
如果没有就插入。
对于主键自增的场景,
一般不会手动设置id,每一次的id都不相同,
所以如果不使用条件选择器,一定是插入。