简化mybatis @Select IN条件的编写

最近从JPA切换到Mybatis,使用无XML配置,@Select注解直接写到interface上,发现IN条件的编写相当麻烦。

一般得写成这样:

java 复制代码
@Select({"<script>",
         "SELECT *", 
         "FROM blog",
         "WHERE id IN", 
           "<foreach item='item' index='index' collection='list'",
             "open='(' separator=',' close=')'>",
             "#{item}",
           "</foreach>",
         "</script>"}) 
List<Blog> selectBlogs(@Param("list") int[] ids);

写的看起来很别扭,原来JPA+Hibernate写HQL就不用额外处理。想着找一下解决方案,一搜确实也有人有同样的痛点。

原来我写的是这样的:

java 复制代码
    @Select(
        "select distinct(USER_ID) from SYS_LOGIN_LOG " +
        "where USER_ID IN (#{userIds}) " +
        "and TENANT_ID = #{tenantId} " +
        "and CREATE_TIME between #{startTime} and #{endTime}")
    List<Long> selectInTimeRange(
        @Param("userIds") long[] userIds, @Param("tenantId") long tenantId,
        @Param("startTime") Date startTime, @Param("endTime") Date endTime
    );

发现解析失败,google了一下,通过增加一个语法处理器就解决了。

在Mapper基类添加这样的处理器

java 复制代码
public interface CcBaseMapper<T> extends BaseMapper<T> {

    /**
     * 解决mybatis in条件写得难看的问题
     */
    class InConditionDriver extends XMLLanguageDriver
            implements LanguageDriver {
        private final Pattern inPattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)");
        public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
            Matcher matcher = inPattern.matcher(script);
            if (matcher.find()) {
                script = matcher.replaceAll("(<foreach collection=\"$1\" item=\"__item\" separator=\",\" >#{__item}</foreach>)");
            }
            script = "<script>" + script + "</script>";
            return super.createSqlSource(configuration, script, parameterType);
        }
    }

然后添加这个处理器即可:

java 复制代码
    @Lang(InConditionDriver.class)
    @Select(
        "select distinct(USER_ID) from SYS_LOGIN_LOG " +
        "where USER_ID IN (#{userIds}) " +
        "and TENANT_ID = #{tenantId} " +
        "and CREATE_TIME between #{startTime} and #{endTime}")
    List<Long> selectInTimeRange(
        @Param("userIds") long[] userIds, @Param("tenantId") long tenantId,
        @Param("startTime") Date startTime, @Param("endTime") Date endTime
    );

这样就不报错了。搞掂

相关推荐
未来之窗软件服务2 小时前
幽冥大陆(二十二)dark语言智慧农业电子秤读取——东方仙盟炼气期
开发语言·windows·golang·东方仙盟·东方仙盟sdk
黎茗Dawn4 小时前
git-Windows-my-dell-笔记
开发语言·windows·git
2501_915921437 小时前
Windows 系统下的 IPA 加密工具实战指南,如何在非 macOS 环境完成 IPA 混淆、加固与工程化处理
android·windows·macos·ios·小程序·uni-app·iphone
q***71018 小时前
如何在Windows系统上安装和配置Node.js及Node版本管理器(nvm)
windows·node.js
朝新_8 小时前
【实战】博客系统:项目公共模块 + 博客列表的实现
数据库·笔记·sql·mybatis·交互·javaee
珂玥c9 小时前
ubuntu20.04设备启用windows虚拟机
windows
小小哭包10 小时前
Spring Boot整合多个MyBatis数据源实战教程
spring boot·后端·mybatis
广师大-Wzx12 小时前
JavaSE进阶(Day12)
java·数据结构·windows
p***976119 小时前
从零开始在Windows系统上搭建一个node.js后端服务项目
windows·node.js
b***91021 小时前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
android·前端·后端·mybatis