去年年底的因为业务需要需要在使用tk.mybaits框架的系统中实现指定字段的更新,可是tk.mybaits框架本身并不支持这个功能,我翻遍了优快云和其他相关的技术相关的网站都没有找到相关的解决方法。于是我通过几天的翻阅相关资料和摸索后终于实现了这个功能。最近事情不是很多,想到又想到了去年解决的这个问题,于是有了这篇文章。分享一下当时的解决方法,为有同样需求的小伙伴抛砖引玉。
这个问题如果系统使用的是Mybatis-Plus框架的话,实现只更新指定的字段是一件很简单的事情。只需要写以下代码即可:
UpdateWrapper updateWrapper = new UpdateWrapper();
updateWrapper.eq("id", 1);
updateWrapper.set("status", 1);
updateWrapper.set("nickname", "张三");
baseMapper.update(null, updateWrapper);
但是如果系统使用的是tk.mybaits则默认不支持这个功能,有一种迂回的解决的办法是现查询出对应的数据,在set需要更新的字段,再更新整条数据。但是这样终究不是很好,在并发情况下也很容易出现问题。至于tk.mybaits指定字段更新的方案,我在网上找了很久都没有找到相关的解决方法。随后我通过分析tk.mybaits在github的源码和issue回答找到些许线索。最终实现了这个功能。具体结局方案如下:
先定义一个名为UpdateAppointColumnMapper接口
/**
* @author: jie
* @create: 2022/11/15 10:55
* @description: 通用Mapper接口,更新指定字段,实现
*/
@tk.mybatis.mapper.annotation.RegisterMapper
public interface UpdateAppointColumnMapper<T> {
/**
* 根据Example条件更新实体`record`包含的不是null的属性值
*
* @param record
* @param example
* @return
*/
@UpdateProvider(type = UpdateByExampleAppointColumnProvider.class, method = "dynamicSQL")
int updateByExampleAppointColumn(@Param("record") T record, @Param("example") Object example,@Param("updateColumns") List<String> updateColumns);
//
// @UpdateProvider(type = UpdateByExampleAppointColumnExampleProvider2.class, method = "updateByExampleAppointColumn")
// int updateByExampleAppointColumn2(@Param("record") T record, @Param("example") Object example,@Param("updateColumns") List<String> updateColumns);
/**
* 根据Example条件更新实体`record`包含的不是null的属性值
*
* @param record
* @param example
* @return
*/
@UpdateProvider(type = UpdateByExampleAppointColumnProvider.class, method = "dynamicSQL")
int updateByExampleAppointColumnForMap(@Param("record") Map record, @Param("example") Object example, @Param("updateColumns") List<String> updateColumns);
}
再定义一个名为UpdateByExampleAppointColumnProvider的Provider(核心代码)
/**
* @author: jie
* @create: 2022/11/16 19:00
* @description:
*/
public class UpdateByExampleAppointColumnProvider extends MapperTemplate {
public static final String UPDATE_PROPERTIES = "updateColumns";
public UpdateByExampleAppointColumnProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
super(mapperClass, mapperHelper);
}
/**
* 根据Example更新非null字段
*
* @param ms
* @return
*/
public String updateByExampleAppointColumn(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
ParameterMap paramterType = ms.getParameterMap();
Configuration configuration = ms.getConfiguration();
MetaObject metaObject = MetaObjectUtil.forObject(ms);
SqlSource sqlSource = ms.getSqlSource();
//BoundSql boundSql = sqlSource.getBoundSql(entityClass);
StringBuilder sql = new StringBuilder();
if (isCheckExampleEntityClass()) {
sql.append

文章介绍了在tk.mybatis.mapper框架中,如何实现像Mybatis-Plus一样更新指定字段的功能。作者通过分析源码和创建自定义Mapper接口及Provider,提供了一种动态SQL的解决方案,包括创建UpdateAppointColumnMapper接口和UpdateByExampleAppointColumnProvider类,以及如何在实际使用中应用这些自定义组件来更新指定字段。
最低0.47元/天 解锁文章
790

被折叠的 条评论
为什么被折叠?



