【原创】MybatisPlus调用原生SQL的三种方法

前言

在有些情况下需要用到MybatisPlus查询原生SQL,MybatisPlus其实带有运行原生SQL的方法,我这里列举三种

方法一

这也是网上流传最广的方法,但是我个人认为这个方法并不优雅,且采用${}的方式代码审计可能会无法通过,会被作为代码漏洞

public interface BaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> {

    @Select("${nativeSql}")
    Object nativeSql(@Param("nativeSql") String nativeSql);
}

使用一个自己的BaseMapper去继承MybatisPlus自己的BaseMapper,然后所有的Mapper去继承自己写的BaseMapper即可。那么所有的Mapper都能查询原生SQL了。

问题在于${nativeSql}可能会被作为代码漏洞,我并不提倡这种写法。

方法二

使用SqlRunner的方式执行原生SQL。这个方法我较为提倡,也是MybatisPlus源码的测试类中用的最多的方法。

下图为MybatisPlus源码的测试类:

 要使用SqlRunner的前提是打开SqlRunner,编辑application.yaml增加配置如下:

mybatis-plus:
  global-config:
    enable-sql-runner: true

application.properties写法:

mybatis-plus.global-config.enable-sql-runner=true

如果不打开会报

Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxxxxxx

使用方法:

List<Map<String, Object>> mapList = SqlRunner.db().selectList("select * from test_example limit 1,10");

我个人比较推荐使用这种方式来查询原生SQL,既不会污染Mapper,也不会被报出代码漏洞。

方法三

采用原始的洪荒之力,用Mybatis最底层的方式执行原生SQL

        String sql = "select * from test_example limit 1,10";

        Class<ExampleEntity> entityClass = ExampleEntity.class;
        // INFO: DCTANT: 2022/9/29 使用MybatisPlus自己的SqlHelper获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = SqlHelper.sqlSessionFactory(ExampleEntity.class);
        // INFO: DCTANT: 2022/9/29 通过SqlSessionFactory创建一个新的SqlSession,并获取全局配置
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Configuration configuration = sqlSessionFactory.getConfiguration();

        // INFO: DCTANT: 2022/9/29 生成一个uuid,用于将这个SQL创建的MappedStatement注册到MybatisPlus中
        String sqlUuid = UUID.fastUUID().toString(true);
        RawSqlSource rawSqlSource = new RawSqlSource(configuration, sql, Object.class);
        MappedStatement.Builder builder = new MappedStatement.Builder(configuration, sqlUuid, rawSqlSource, SqlCommandType.SELECT);
        ArrayList<ResultMap> resultMaps = new ArrayList<>();
        // INFO: DCTANT: 2022/9/29 创建返回映射 
        ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, UUID.fastUUID().toString(true), entityClass, new ArrayList<>());
        ResultMap resultMap = resultMapBuilder.build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);

        MappedStatement mappedStatement = builder.build();
        // INFO: DCTANT: 2022/9/29 将创建的MappedStatement注册到配置中
        configuration.addMappedStatement(mappedStatement);
        // INFO: DCTANT: 2022/9/29 使用SqlSession查询原生SQL 
        List<ExampleEntity> list = sqlSession.selectList(sqlUuid);
        // INFO: DCTANT: 2022/9/29 关闭session 
        sqlSession.close();

其中的UUID是Hutool中的方法,用于生成随机字符串。

这个方法就不需要打开SqlRunner了,就是代码量感人,我不是很推荐,但是能够窥探一下MybatisPlus的底层逻辑。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>