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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

前言

在有些情况下需要用到MybatisPlus查询原生SQLMybatisPlus其实带有运行原生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的底层逻辑。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6