简化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
    );

这样就不报错了。搞掂

相关推荐
小坏讲微服务20 小时前
Spring Boot 4.0 新特性整合 MyBatis-Plus 完整教程
java·spring boot·后端·spring cloud·微服务·mybatis·mybatis plus
我命由我1234520 小时前
Java 开发使用 MyBatis PostgreSQL 问题:传入的参数为 null,CONCAT 函数无法推断参数的数据类型
java·开发语言·数据库·学习·postgresql·mybatis·学习方法
YDS82920 小时前
MyBatis-Plus —— 扩展功能详解
数据库·mybatis
飞Link1 天前
Windows 环境下 LaTeX 的安装配置教程
windows·vscode
R.lin1 天前
windows MySQL解压版安装教程
windows·mysql·adb
常家壮1 天前
Windows隐藏账号创建完全指南:技术原理与安全实践
windows·安全·渗透测试·后门·windows隐藏账号
真上帝的左手1 天前
18. 操作系统-Windows-命令提示符
windows
GHL2842710901 天前
文件重命名(C++源码)
前端·c++·windows
。小二2 天前
springboot3实现aop多数据源结合mybatis-plus-boot-starter
java·spring boot·spring·mybatis
CUIYD_19892 天前
MyBatis 的一级缓存
java·缓存·mybatis