mybatis-plus 属性为空时判断问题

mybatis-plus 属性为空时判断问题

最近在做项目时,发现前端调用查询接口,发现接口返回数据不对。我通过日志发现前端查询字段值为空时,竟然被当作一个条件,因为后端采用的mybatis-plus,通过官网我找到了一个配置

mybatis-plus:
  global-config:
    db-config:
      select-strategy: not_empty

然后再测试一遍发现好使了。
我决定看一下mybatis-plus的底层时怎么实现的。
mybatis-plus 为我们提供了许多默认的方法,通过继承BaseMapper就可以实现,无需配置xml,具体的方法可以参考mybatis-plus的官方网站:
mybatis-plus

   mybatis 在启动的时候,会根据mapper方法,生成一个MappedStatement,一个mapper的方法会对应一个MappedStatement.
public final class MappedStatement {

  private String resource;
  private Configuration configuration;
  private String id;
  private Integer fetchSize;
  private Integer timeout;
  private StatementType statementType;
  private ResultSetType resultSetType;
  private SqlSource sqlSource;
  private Cache cache;
  private ParameterMap parameterMap;
  private List<ResultMap> resultMaps;
  private boolean flushCacheRequired;
  private boolean useCache;
  private boolean resultOrdered;
  private SqlCommandType sqlCommandType;
  private KeyGenerator keyGenerator;
  private String[] keyProperties;
  private String[] keyColumns;
  private boolean hasNestedResultMaps;
  private String databaseId;
  private Log statementLog;
  private LanguageDriver lang;
  private String[] resultSets;

由此可以想到,mybatis-plus 启动的时候会生成一些默认的方法的 MappedStatement我们先看MybatisConfiguration 的addMapper 方法

    @Override
    public <T> void addMapper(Class<T> type) {
        mybatisMapperRegistry.addMapper(type);
    }

跳转到MybatisMapperRegistry 类中

 @Override
    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                // TODO 如果之前注入 直接返回
                return;
                // TODO 这里就不抛异常了
//                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                // TODO 这里也换成 MybatisMapperProxyFactory 而不是 MapperProxyFactory
                knownMappers.put(type, new MybatisMapperProxyFactory<>(type));
                // It's important that the type is added before the parser is run
                // otherwise the binding may automatically be attempted by the
                // mapper parser. If the type is already known, it won't try.
                // TODO 这里也换成 MybatisMapperAnnotationBuilder 而不是 MapperAnnotationBuilder
                MybatisMapperAnnotationBuilder parser = new MybatisMapperAnnotationBuilder(config, type);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }

重点看 parser.parse() 我们在点进去看

 @Override
    public void parse() {
        String resource = type.toString();
        if (!configuration.isResourceLoaded(resource)) {
            loadXmlResource();
            configuration.addLoadedResource(resource);
            final String typeName = type.getName();
            assistant.setCurrentNamespace(typeName);
            parseCache();
            parseCacheRef();
            SqlParserHelper.initSqlParserInfoCache(type);
            Method[] methods = type.getMethods();
            for (Method method : methods) {
                try {
                    // issue #237
                    if (!method.isBridge()) {
                        parseStatement(method);
                        SqlParserHelper.initSqlParserInfoCache(typeName, method);
                    }
                } catch (IncompleteElementException e) {
                    // TODO 使用 MybatisMethodResolver 而不是 MethodResolver
                    configuration.addIncompleteMethod(new MybatisMethodResolver(this, method));
                }
            }
            // TODO 注入 CURD 动态 SQL , 放在在最后, because 可能会有人会用注解重写sql
            if (GlobalConfigUtils.isSupperMapperChildren(configuration, type)) {
                GlobalConfigUtils.getSqlInjector(configuration).inspectInject(assistant, type);
            }
        }
        parsePendingMethods();
    }

我们看inspectInject方法:

@Override
    public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
        Class<?> modelClass = extractModelClass(mapperClass);
        if (modelClass != null) {
            String className = mapperClass.toString();
            Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
            if (!mapperRegistryCache.contains(className)) {
                List<AbstractMethod> methodList = this.getMethodList(mapperClass);
                if (CollectionUtils.isNotEmpty(methodList)) {
                	//包装一个实体类
                    TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
                    // 循环注入自定义方法
                    methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
                } else {
                    logger.debug(mapperClass.toString() + ", No effective injection method was found.");
                }
                mapperRegistryCache.add(className);
            }
        }
    }

然后再看 m.inject方法:

  /**
     * 注入自定义方法
     */
    public void inject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        this.configuration = builderAssistant.getConfiguration();
        this.builderAssistant = builderAssistant;
        this.languageDriver = configuration.getDefaultScriptingLanguageInstance();
        /* 注入自定义方法 */
        injectMappedStatement(mapperClass, modelClass, tableInfo);
    }

终于看到增加MappedStatement了,injectMappedStatement有很多实现类

在这里插入图片描述
因为是查询 我们看selectList

@Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlMethod sqlMethod = SqlMethod.SELECT_LIST;
        String sql = String.format(sqlMethod.getSql(), sqlSelectColumns(tableInfo, true),
            tableInfo.getTableName(), sqlWhereEntityWrapper(true, tableInfo),
            sqlComment());
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForTable(mapperClass, sqlMethod.getMethod(), sqlSource, tableInfo);
    }

因为是查询条件,我们看sqlWhereEntityWrapper 方法 此方法会封装一些sql的条件语句:,最后来到TableFieldInfo的getSqlWhere方法:

 public String getSqlWhere(final String prefix) {
        final String newPrefix = prefix == null ? EMPTY : prefix;
        // 默认:  AND column=#{prefix + el}
        String sqlScript = " AND " + String.format(condition, column, newPrefix + el);
        // 查询的时候只判非空
        return convertIf(sqlScript, newPrefix + property, whereStrategy);
    }

然后进入convertIf方法:

private String convertIf(final String sqlScript, final String property, final FieldStrategy fieldStrategy) {
        if (fieldStrategy == FieldStrategy.NEVER) {
            return null;
        }
        if (fieldStrategy == FieldStrategy.IGNORED) {
            return sqlScript;
        }
        if (fieldStrategy == FieldStrategy.NOT_EMPTY && isCharSequence) {
            return SqlScriptUtils.convertIf(sqlScript, String.format("%s != null and %s != ''", property, property),
                false);
        }
        return SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", property), false);
    }

通过代码可以看到生成的sql条件对空判断和策略有关,那我们就去找TableFieldInfo创建的时候是怎么赋值的,我们回到AbstractSqlInjector中

@Override
    public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
        Class<?> modelClass = extractModelClass(mapperClass);
        if (modelClass != null) {
            String className = mapperClass.toString();
            Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
            if (!mapperRegistryCache.contains(className)) {
                List<AbstractMethod> methodList = this.getMethodList(mapperClass);
                if (CollectionUtils.isNotEmpty(methodList)) {
                    TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
                    // 循环注入自定义方法
                    methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
                } else {
                    logger.debug(mapperClass.toString() + ", No effective injection method was found.");
                }
                mapperRegistryCache.add(className);
            }
        }
    }

TableFieldInfo 是TableInfo的属性,我们看initTableInfo方法:

   /* 初始化字段相关 */
        initTableFields(clazz, globalConfig, tableInfo);

此方法就是创建TableFieldInfo:

   /* 无 @TableField 注解的字段初始化 */
            fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field));

然后看TableFieldInfo的构造方法:

 public TableFieldInfo(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo, Field field) {
        this.version = field.getAnnotation(Version.class) != null;
        this.property = field.getName();
        this.propertyType = field.getType();
        this.isCharSequence = StringUtils.isCharSequence(this.propertyType);
        this.el = this.property;
        this.insertStrategy = dbConfig.getInsertStrategy();
        this.updateStrategy = dbConfig.getUpdateStrategy();
        this.whereStrategy = dbConfig.getSelectStrategy();
        tableInfo.setLogicDelete(this.initLogicDelete(dbConfig, field));

可以看到this.whereStrategy = dbConfig.getSelectStrategy();
就是说这个策略可以配置来改变

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: Mybatis-Plus提供了多种方式进行批量插入优化,以下是几种常用的方法: 1. 使用Mybatis-Plus提供的BatchInsert方法进行批量插入,可以大大减少SQL语句的执行次数,提高插入效率。 2. 使用Mybatis-Plus提供的BatchInsertMappedStatement方法进行批量插入,可以将多个插入操作合并为一个SQL语句,减少数据库的IO操作,提高插入效率。 3. 使用Mybatis-Plus提供的BatchInsertSelective方法进行批量插入,可以只插入非字段,减少插入的数据量,提高插入效率。 4. 使用Mybatis-Plus提供的BatchInsertOrUpdate方法进行批量插入或更新,可以根据主键进行判断,如果存在则更新,不存在则插入,提高插入效率。 总之,Mybatis-Plus提供了多种方式进行批量插入优化,可以根据具体的业务需求选择合适的方法进行优化,提高插入效率。 ### 回答2: Mybatis-Plus是一款优秀的ORM框架,通过简化SQL,并提供了便捷的CRUD操作,为Java开发者提供了方便快捷的开发体验。在数据量较大的情况下,批量插入优化是一个非常关键的技术点。下面我们来谈谈Mybatis-Plus如何进行批量插入的优化。 1、使用自增主键 - 我们可以将主键设置为自增类型,这样就可以通过Mybatis-Plus自动生成主键,避免在批量插入多次查询主键。 2、使用BatchExecutor - Mybatis-Plus提供了BatchExecutor来执行批量插入操作,这样可以避免在单条插入过程中频繁的开启和关闭数据库连接,从而提高了效率。 3、使用JDBC Batch - 在使用BatchExecutor的候,我们可以选择使用JDBC Batch机制,这样可以将多个SQL语句存放到一个批处理中,然后一次性执行。通过这种方式可以大大减少与数据库交互的次数。 4、使用Mybatis-Plus自带的批量插入方法 - Mybatis-Plus提供了一个批量插入方法,可以在一次SQL语句中同插入多条数据。使用该方法会显著提高数据插入效率。 5、适当分批 - 如果我们需要插入的数据量巨大,即使使用了批量插入的方式,也会出现内存溢出等问题。这候我们可以将数据集合分成若干个小批次,每次只处理部分数据,最后再合并成一条记录。这样既可以保证数据的完整性,还可以避免出现问题。 以上就是Mybatis-Plus批量插入优化的常见策略,通过优化可以大幅提升插入效率,并节省数据库资源。 ### 回答3: mybatis-plus是基于mybatis二次开发的一个ORM框架,提供了很多实用的增删改查方法,方便了开发人员的工作。其中一个常见的需求就是批量插入数据,因为单条插入数据效率低下,会导致数据库连接大量占用,影响系统性能。因此,如何优化mybatis-plus的批量插入就成为了开发人员需要关注的一个问题mybatis-plus提供了两种方式进行批量操作:insertBatch和insertBatchSomeColumn。insertBatch是完全插入,即将所有的属性都插入到数据库中,而insertBatchSomeColumn则可以选择要插入的属性,只将选择的属性插入到数据库中。下面我们具体介绍一下如何优化这两种批量插入方式。 对于insertBatch,我们可以通过三种方式进行优化: 1.使用JDBC批处理:在使用insertBatch方法mybatis-plus会为每一条数据都生成一条插入语句,这显然会消耗大量的数据库连接资源。因此我们可以通过JDBC批处理,批量生成插入语句,减少数据库连接的占用。 2.使用mybatis-plus的插件:mybatis-plus提供了一个BatchInsertPlugin插件,可以将多条插入语句合并为一条,从而减少数据库连接的占用。 3.调整批处理大小:mybatis-plus默认的批处理大小是1000,我们可以根据实际情况调整该值,从而达到更好的性能优化效果。 对于insertBatchSomeColumn,我们可以通过两种方式进行优化: 1.使用mybatis-plus的插件:mybatis-plus提供了一个BatchInsertColumnSomePlugin插件,可以将多条插入语句合并为一条,从而减少数据库连接的占用。 2.调整批处理大小:和insertBatch相同,我们也可以根据实际情况调整批处理大小,从而达到更好的性能优化效果。 综合来说,通过JDBC批处理、mybatis-plus插件和调整批处理大小等方式,可以有效地优化mybatis-plus的批量插入性能,提高系统的整体性能和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值