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

这样就不报错了。搞掂

相关推荐
Karl_wei1 小时前
桌面应用开发,Flutter 与 Electron如何选
windows·flutter·electron
未名编程4 小时前
Windows 下如何部署 Nacos 并导入配置文件
java·windows
R***62315 小时前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
2501_941885966 小时前
智能物流配送优化系统开发与多语言微服务实践:Python、Java、C++与Go全栈实现解析
windows
梅梅绵绵冰6 小时前
ssm整合框架
数据库·mybatis
p***s917 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
lihui_cbdd7 小时前
幽灵卡顿:Windows 11 “数据正常但系统卡死“ 的深度排查与终极优化指南
windows
林抒8 小时前
(2025版)MongoDB 8.0.13 版本安装与配置(Windows 版)保姆级教程
windows·mongodb·nosql数据库
nbsaas-boot8 小时前
JPA vs MyBatis 在大型 SaaS 架构中的使用边界
spring·架构·mybatis
i***66508 小时前
Spring-boot3.4最新版整合swagger和Mybatis-plus
mybatis