myatisplus的saveOrUpdate的提交總是update問題
背景
很多朋友,想把新增和編輯做在一起。
沒想到自己遇到坑了,
自己的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); // 根據(jù)updateWrapper嘗試更新,否繼續(xù)執(zhí)行saveOrUpdate(T)方法 boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
分析
發(fā)現(xiàn)上面的sql沒有where條件。
以為是新增操作,沒有id,主鍵是自增的,就加了個判斷
ObjectUtils.isNotEmpty(courseTypeId)。
發(fā)現(xiàn)是updateWrapper的eq方法 不能加condition參數(shù)。
錯誤方式
updateWrapper.eq(ObjectUtils.isNotEmpty(courseTypeId), CourseTypeEntity::getCourseTypeId, courseTypeId);
正確方式
去除第一個condition參數(shù)。保留2個參數(shù)即可。
updateWrapper.eq(CourseTypeEntity::getCourseTypeId, courseTypeId);
成功案例實現(xiàn)源碼分享
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都不相同,
所以如果不使用條件選擇器,一定是插入。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring配置多個數(shù)據(jù)源并實現(xiàn)數(shù)據(jù)源的動態(tài)切換功能
這篇文章主要介紹了Spring配置多個數(shù)據(jù)源并實現(xiàn)數(shù)據(jù)源的動態(tài)切換功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01詳解Spring的兩種代理方式:JDK動態(tài)代理和CGLIB動態(tài)代理
這篇文章主要介紹了詳解Spring的兩種代理方式:JDK動態(tài)代理和CGLIB動態(tài)代理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04