Mybatis-Plus中saveOrUpdate方法的使用 及 注意事项
saveOrUpdate不传入updateWrapper 通过主键更新数据。saveOrUpdate传入updateWrapper 通过传入的字段更新数据。传入updateWrapper源码分析:先尝试通过传入字段更新,更新成功直接返回;更新失败,再通过saveOrUpdate(entity)更新,但通过saveOrUpdate(entity)更新就是通过主键插入了。在指定字段更新时,会更新除了i
文章共538字 · 阅读需要大约2分钟
一键AI生成摘要,助你高效阅读
问答
·
01.出现的问题
一般情况下,数据库更新表时都是用一个字段更新,一般是ID字段,即updateById。
但最近在生产任务中用到了通过两个字段更新数据库的情况。
02.问题分析
从其他系统同步数据过来时,数据带有标识符,标识符为“I” 时为插入,UN 时为更新。
这时判断标识符,将实体对象封装好后传入saveOrUpdate方法即可通过主键 Id 更新数据库。
if ("UN".equals(operation) || "I".equals(operation.trim())) {
xxxService.saveOrUpdate(entity);
}
但现生产上需要根据两个非主键字段更新数据库,我想到了向saveOrUpdate方法中传入updateWrapper
03.尝试问题解决
使用传入updateWrapper的saveOrUpdate 方法
if ("UN".equals(operation) || "I".equals(operation.trim())) {
//rrAssetEntityService.saveOrUpdate(rrAssetEntity);
UpdateWrapper<RrAssetEntity> updateWrapper = new UpdateWrapper<RrAssetEntity>()
.eq("rr_asset_entity.asset_id", rrAssetEntity.getAssetId())
.eq("rr_asset_entity.entity_id", rrAssetEntity.getEntityId());
rrAssetEntityService.saveOrUpdate(rrAssetEntity, updateWrapper); //这个方法更新(update)时不更新主键字段,保存(save)时会保存所有字段
auditAssetEntity.setIsProcess("1");
}
成功解决问题
04.总结和注意事项
saveOrUpdate不传入updateWrapper 通过主键更新数据。
saveOrUpdate传入updateWrapper 通过传入的字段更新数据。
传入updateWrapper源码分析:先尝试通过传入字段更新,更新成功直接返回;更新失败,再通过saveOrUpdate(entity)更新,但通过saveOrUpdate(entity)更新就是通过主键插入了。
在指定字段更新时,会更新除了id之外的其他所有字段,但不会更新id
若指定字段更新失败,就会使用主键更新saveOrUpdate方法,需要注意这点
更多推荐
已为社区贡献1条内容
所有评论(0)