服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - mybatis-plus支持null字段全量更新的两种方法

mybatis-plus支持null字段全量更新的两种方法

2023-03-09 13:42起风哥 Java教程

本文主要介绍了mybatis-plus支持null字段全量更新的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

背景

如果仅仅只是标题所列的目标,那么mybatis-plus 中可以通过设置
mybatis-plus.global-config.db-config.field-strategy=ignored
来忽略null判断,达到实体字段为null时也可以更新数据为null
但是一旦使用了这个策略,就相当于所有业务代码都会按照这个策略执行。
但是我们的业务往往需要如下支持
1、支持null字段全部更新
2、支持非null更新
3、支持指定null字段更新

所以单独设置某一个策略是很难满足实际的业务场景,因此我们需要在写具体业务代码的时候能够根据需要选择合适的方式。

mybatis-plus字段的四种策略

  • default 默认的,一般只用于注解里
    • 在全局里代表 NOT_NULL
    • 在注解里代表 跟随全局
  • ignored 忽略判断
  • not_empty 非空判断
  • not_null 非NULL判断

这四种策略既可以配置全局,也可以在实体的注解上配置,但是,配置之后就是死的玩意,无法动态。

一般默认情况下都是not_null,如果此时要更新为null,那么用lambdaUpdateWrapper手动设置哪些字段需要更新为null:
如将userName字段更新为null

?
1
2
3
4
userService.update(
                Wrappers.lambdaUpdate(user)
                        .set(User::getUserName, null)
                        .eq(User::getId,"0001"));

很显然字段较少时这个方案还能说的过去,但是我们既有很少字段的情况,也有大批量字段的情况
所以此时使用这种方案很明显的使用起来非常难受,那么有没有方案既能支持有值更新,又能支持指定更新,还能
支持全量更新呢?
答案是有的,提供一个最低成本的适配方案如下

方案一

全局设置字段策略为not_null
因为本身LambdaUpdateWrapper 已经满足了单个设置的需求,所以我们在写个方法把全部字段组装起来即可,
当然此处的全部字段肯定也不是真的全部字段比如:一些比较特别的字段就不能被更新为null公共的字段创建时间,更新时间,逻辑删除字段等等。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class WrappersFactory {
 
    private final static List<String> ignoreList = new ArrayList<>();
 
    static {
        ignoreList.add(CommonField.available);
        ignoreList.add(CommonField.create_time);
        ignoreList.add(CommonField.create_username);
        ignoreList.add(CommonField.update_time);
        ignoreList.add(CommonField.update_username);
        ignoreList.add(CommonField.create_user_code);
        ignoreList.add(CommonField.update_user_code);
        ignoreList.add(CommonField.deleted);
    }
 
    public static <T> LambdaUpdateWrapper<T> updateWithNullField(T entity) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        List<Field> allFields = TableInfoHelper.getAllFields(entity.getClass());
        MetaObject metaObject = SystemMetaObject.forObject(entity);
        for (Field field : allFields) {
            if (!ignoreList.contains(field.getName())) {
                Object value = metaObject.getValue(field.getName());
                updateWrapper.set(StringUtils.camelToUnderline(field.getName()), value);
            }
        }
        return updateWrapper.lambda();
    }
}

使用

?
1
userService.update(WrappersFactory.updateWithNullField(user).eq(User::getId,"0001"));

方案二

此方案采用的是常规的mybatis-plus扩展
实际就是实现 IsqlInjector

定义个方法

?
1
2
3
4
5
6
7
public class UpdateWithNull extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        //具体的字段逻辑在这里处理,实际上就是在这里构造一个新的statement
        return null;
    }
}

定义个CommonMapper继承自BaseMapper,然后让你的所有Mapper继承自CommonMapper

?
1
2
3
4
5
6
7
8
9
10
11
public interface CommonMapper <T> extends BaseMapper<T> {
 
    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int updateWithNull(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
 
}

声明一个IsqlInjector,然后将其配置为spring的bean即可

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class CustomSqlInjector extends AbstractSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList() {
        return Stream.of(
                new Insert(),
                new Delete(),
                new DeleteByMap(),
                new DeleteById(),
                new DeleteBatchByIds(),
                new Update(),
                new UpdateWithNull(),
                new UpdateById(),
                new SelectById(),
                new SelectBatchByIds(),
                new SelectByMap(),
                new SelectOne(),
                new SelectCount(),
                new SelectMaps(),
                new SelectMapsPage(),
                new SelectObjs(),
                new SelectList(),
                new SelectPage()
        ).collect(toList());
    }
}

 方案二个人认为没有什么必要,这种扩展方式是为了增加一些mybatis-plus未支持的定式需求。而我们的目标相对简单,所以使用方案一更高效。

方案二原理介绍

TableFieldInfo#getSqlSet

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public String getSqlSet(final String prefix) {
        final String newPrefix = prefix == null ? EMPTY : prefix;
        // 默认: column=
        String sqlSet = column + EQUALS;
        if (StringUtils.isNotEmpty(update)) {
            sqlSet += String.format(update, column);
        } else {
            sqlSet += SqlScriptUtils.safeParam(newPrefix + el);
        }
        sqlSet += COMMA;
        if (fieldFill == FieldFill.UPDATE || fieldFill == FieldFill.INSERT_UPDATE) {
            // 不进行 if 包裹
            return sqlSet;
        }
        return convertIf(sqlSet, newPrefix + property);
    }

可以看到这段代码的逻辑中有一行fieldFill判断,为update或者insert_update时不进行if包裹。我们能可以利用这个特性。直接将需要的非公共字段全部设置为FieldFill.UPDATE即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
final List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        for (final TableFieldInfo tableFieldInfo : fieldList) {
            final Class<? extends TableFieldInfo> aClass = tableFieldInfo.getClass();
            try {
                final Field fieldFill = aClass.getDeclaredField("fieldFill");
                fieldFill.setAccessible(true);
                fieldFill.set(tableFieldInfo, FieldFill.UPDATE);
            } catch (final NoSuchFieldException e) {
                log.error("获取fieldFill失败", e);
            } catch (final IllegalAccessException e) {
                log.error("设置fieldFill失败", e);
            }
        }

所以这里的具体逻辑为

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Slf4j
public class UpdateWithNull extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlMethod sqlMethod = SqlMethod.UPDATE;
 
        final List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        for (final TableFieldInfo tableFieldInfo : fieldList) {
            final Class<? extends TableFieldInfo> aClass = tableFieldInfo.getClass();
            try {
                final Field fieldFill = aClass.getDeclaredField("fieldFill");
                fieldFill.setAccessible(true);
                fieldFill.set(tableFieldInfo, FieldFill.UPDATE);
            } catch (final NoSuchFieldException e) {
                log.error("获取fieldFill失败", e);
            } catch (final IllegalAccessException e) {
                log.error("设置fieldFill失败", e);
            }
        }
 
        String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
                sqlSet(true, true, tableInfo, true, ENTITY, ENTITY_DOT),
                sqlWhereEntityWrapper(true, tableInfo));
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }
}

到此这篇关于mybatis-plus支持null字段全量更新的两种方法的文章就介绍到这了,更多相关mybatis-plus null全量更新内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/a807719447/article/details/129008176

延伸 · 阅读

精彩推荐