Mybatis手动解析并执行SQL

场景:需要动态生成查询的API接口,实现方式打算每个API底层都配置一个MyBatis动态SQL脚本,然后让Mybatis解析并返回查询结果,那么如果手动让Mybatis帮我们解析动态SQL呢?工具类如下:

public class AutoApiSqlMapper {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    private SqlBuilderStatement SqlBuilderStatement;

    @PostConstruct
    public void init() {
        this.SqlBuilderStatement = new SqlBuilderStatement(sqlSessionFactory.getConfiguration());
    }

    public Map<String, Object> sqlSelectOne(String sql) {
        List<Map<String, Object>> list = this.selectList(sql);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    public List<Map<String, Object>> selectList(String sql) {
        String msId = this.SqlBuilderStatement.select(sql);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            return sqlSession.selectList(msId);
        } finally {
            sqlSession.close();
        }
    }

    public <T> List<T> selectList(String sql, Object value, Class<T> resultType) {
        Class<?> parameterType = value != null ? value.getClass() : null;
        String msId;
        if (resultType == null) {
            msId = this.SqlBuilderStatement.selectDynamic(sql, parameterType);
        } else {
            msId = this.SqlBuilderStatement.selectDynamic(sql, parameterType, resultType);
        }
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            return sqlSession.selectList(msId, value);
        } finally {
            sqlSession.close();
        }
    }

    private static class SqlBuilderStatement {
        private Configuration configuration;
        private LanguageDriver languageDriver;

        private SqlBuilderStatement(Configuration configuration) {
            this.configuration = configuration;
            this.languageDriver = configuration.getDefaultScriptingLanguageInstance();
        }

        private String newMsId(String sql, SqlCommandType sqlCommandType) {
            return sqlCommandType.toString() + "." + sql.hashCode();
        }

        private boolean hasMappedStatement(String msId) {
            return this.configuration.hasStatement(msId, false);
        }

        private void newSelectMappedStatement(String msId, SqlSource sqlSource, final Class<?> resultType) {
            MappedStatement ms = (new MappedStatement.Builder(this.configuration, msId, sqlSource, SqlCommandType.SELECT)).resultMaps(new ArrayList<ResultMap>() {
                {
                    this.add((new ResultMap.Builder(SqlBuilderStatement.this.configuration, "defaultResultMap", resultType, new ArrayList(0))).build());
                }
            }).build();
            this.configuration.addMappedStatement(ms);
        }

        private String select(String sql, Class<?> resultType) {
            String msId = this.newMsId(resultType + sql, SqlCommandType.SELECT);
            if (!this.hasMappedStatement(msId)) {
                StaticSqlSource sqlSource = new StaticSqlSource(this.configuration, sql);
                this.newSelectMappedStatement(msId, sqlSource, resultType);
            }
            return msId;
        }

        private String select(String sql) {
            String msId = this.newMsId(sql, SqlCommandType.SELECT);
            if (!this.hasMappedStatement(msId)) {
                StaticSqlSource sqlSource = new StaticSqlSource(this.configuration, sql);
                this.newSelectMappedStatement(msId, sqlSource, Map.class);
            }
            return msId;
        }

        private String selectDynamic(String sql, Class<?> parameterType) {
            String msId = this.newMsId(sql + parameterType, SqlCommandType.SELECT);
            if (!this.hasMappedStatement(msId)) {
                SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, parameterType);
                this.newSelectMappedStatement(msId, sqlSource, Map.class);
            }
            return msId;
        }

        private String selectDynamic(String sql, Class<?> parameterType, Class<?> resultType) {
            String msId = this.newMsId(resultType + sql + parameterType, SqlCommandType.SELECT);
            if (!this.hasMappedStatement(msId)) {
                SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, parameterType);
                this.newSelectMappedStatement(msId, sqlSource, resultType);
            }
            return msId;
        }
    }
}

单测:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Application.class)
public class AutoApiSqlTest {

    @Autowired
    private AutoApiSqlMapper autoApiSqlMapper;

    @Test
    public void test01() {
        Map<String, String> map = new HashMap<>();
        map.put("id", null);
        //复杂点的查询,这里参数和上面不同的地方,在于传入了一个对象
        List<Map> list = autoApiSqlMapper.selectList("<script>" +
                "select * from position " +
                "   <where>" +
                "       <if test=\"id != null\">" +
                "           id = #{id}" +
                "       </if>" +
                "   </where>" +
                "</script>", map, Map.class);
        System.out.println(JSON.toJSONString(list));
    }
}

 

 

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis的动态SQL是指在SQL语句中根据条件动态地拼接SQL字符串的能力。这个特性可以帮助开发者避免手动拼接SQL字符串时容易出现的错误,比如忘记空格或逗号。动态SQL可以通过使用OGNL表达式进行解析来实现。OGNL是一种表达式语言,可以在MyBatis中使用来创建动态SQL。如果需要在动态SQL中使用除了OGNL表达式以外的变量,可以使用bind标签来创建这些变量。例如,在一个select语句中,可以使用bind标签创建一个名为"pattern"的变量,其值为"'%' + _parameter.getTitle() + '%'",然后在SQL语句中使用#{pattern}来引用这个变量。另外,MyBatis还提供了一些动态标签,比如if标签,可以根据条件来动态地生成SQL语句的一部分。例如,在一个select语句中,可以使用if标签来判断name是否为空,如果不为空,则在SQL语句中添加一个条件。总之,MyBatis的动态SQL功能可以帮助开发者更灵活地生成SQL语句,根据不同的条件动态地拼接SQL字符串。 #### 引用[.reference_title] - *1* [Mybatis动态sql](https://blog.csdn.net/weixin_52394141/article/details/125862192)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [mybatis之动态sql(超详细)](https://blog.csdn.net/xjszsd/article/details/121924231)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值