【实用技巧】【Mybatis】自定义的动态 SQL
1 前言
平时我们可能会拼接 SQL,尤其是做一些报表的开发或者连表查询的时候,当条件发生变更或者关联关系需要改变的时候,就需要更改代码里的 SQL,所以我这里弄了一个简易版的基于 Mybatis的动态 SQL调用。
2 实现
主要是 Mybatis的动态 SQL:
// controller层 @Override @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResultDto<PagerDto<Map>> test(@RequestBody CustomSqlReqDto reqDto) { PagerDto<Map> res = portalService.test(reqDto); return ResultDto.ok(res); } // service层 @Autowired private AccountRepository accountRepository; @Override public PagerDto<Map> test(CustomSqlReqDto reqDto) { CustomSqlPo po = new CustomSqlPo(); po.setMainSql(reqDto.getMainSql()); po.setParam(reqDto.getParam()); po.setSorter(reqDto.getSorter()); po.setHasWhere(reqDto.getHasWhere()); PagerDto<Map> res = accountRepository.test(po); return res; } // repository持久层 @Override public PagerDto<Map> test(CustomSqlPo customSqlPo) { Page<Map> pageParam = new Query<Map>(customSqlPo.getParam(), false).getPage(); Page<Map> page = accountMapper.test(pageParam , customSqlPo.getMainSql() , customSqlPo.getHasWhere() , customSqlPo.getParam() , customSqlPo.getSorter()); PagerDto<Map> res = PagerUtil.changeToPagerDto(page); return res; } // mapper接口 Page<Map> test(Page<Map> pageParam , @Param("mainSql") String mainSql , @Param("hasWhere") Boolean hasWhere , @Param("param") Map<String, Object> param , @Param("sorter") LinkedHashMap<String, Object> sorter); // xml定义模板 <select id="test" resultType="java.util.Map"> ${mainSql} <choose> <when test="hasWhere != null and hasWhere"> <if test="param != null and param.size() > 0"> <foreach collection="param.entrySet()" index="key" item="value"> and ${key} = #{value} </foreach> </if> </when> <otherwise> <if test="param != null and param.size() > 0"> <where> <foreach collection="param.entrySet()" index="key" item="value"> and ${key} = #{value} </foreach> </where> </if> </otherwise> </choose> <if test="sorter != null and sorter.size() > 0"> order by <foreach collection="sorter.entrySet()" index="key" item="value" separator=","> ${key} ${value} </foreach> </if> </select>
大家主要看最后的这个 SQL 模板,有拼条件的,有拼排序的。
3 效果
3.1 单表查询的
3.2 连表查询的
最后大家可以把这样的 SQL 保存到数据库中,每次调用从数据库中获取 SQL。
大家如果有更好的或者有其他更好的主意的还请多多指教哈。
分类:
实用开发技巧
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了