【实用技巧】【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。

大家如果有更好的或者有其他更好的主意的还请多多指教哈。

posted @ 2024-02-08 15:44  酷酷-  阅读(69)  评论(0编辑  收藏  举报