最近项目中开始对接阿里开源的seata分布式事务框架,对接的时候使用update更新数据库记录的时候,应用出现了报错update pk value is not supported!,意思是我使用的tk.mybatis.mapper框架中的updateByExampleSelective等一系列的update语句均会对id进行更新操作,如:
1 | update tableName set id=id, ... |
网上查询资料,决定自定义update的通用方法来解决这个问题。
自定义provider
首先新建一个类来生成对应的update语句。
其中包含了4个update方法:
- updateByPrimaryKeySpecial对应updateByPrimaryKey方法
- updateByPrimaryKeySelectiveSpecial对应updateByPrimaryKeySelective方法
- updateByExampleSelectiveSpecial对应updateByExampleSelective
- updateByExampleSpecial对应updateByExample方法
1 | package com.gugu.core.mybatis.provider; |
这里因为场景问题,这里copy了一份mybatis中的SqlHelper中的代码
只修改了updateSetColumns()的方法中对于主键的更新处理
1 | if (!column.isId() && column.isUpdatable()) { |
新建自定义Mapper
1 | package com.gugu.core.mybatis.mapper; |
SpringBoot中配置
Mybatis默认只支持tk.mybatis.mapper.common.Mapper,会报错误。
1 | Error invoking SqlProvider method (tk.mybatis.mapper.provider.SpecialProvider.dynamicSQL) |
