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

这样就不报错了。搞掂

相关推荐
spencer_tseng11 分钟前
JDK 9 List.of(...)
java·windows·list·1024程序员节
Wind哥11 分钟前
设计模式23种-C++实现
开发语言·c++·windows·设计模式
不平衡的叉叉树14 分钟前
mybatis-plus的insertBatchSomeColumn方法实现批量插入
java·mybatis
忘忧记1 小时前
Excel拆分和合并优化版本
windows·microsoft·excel
m0_674031431 小时前
GitHub等平台形成的开源文化正在重也有人
java·windows·mysql
十碗饭吃不饱2 小时前
RuoYi/ExcelUtil修改(导入excel表时,表中字段没有映射上数据库表字段)
数据库·windows·excel
十五年专注C++开发2 小时前
Drogon: 一个开源的C++高性能Web框架
linux·c++·windows·后端开发·服务器开发
m0_674031432 小时前
GitHub等平台形成的开源文化正在重塑林语堂
windows·mysql·spring
搬砖的小码农_Sky3 小时前
如何从Windows 操作系统登录Linux(Ubuntu)操作系统
linux·windows·ubuntu·远程工作
weixin_438077493 小时前
langchain_neo4j 以及 neo4j (windows-community) 的学习使用
windows·langchain·neo4j