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

这样就不报错了。搞掂

相关推荐
Uncertainty!!7 小时前
Windows 10 与 Ubuntu 22.04 通过 Samba 共享文件夹
windows·ubuntu·共享文件夹
百事牛科技9 小时前
如何创建7Z压缩包?Windows下7-Zip操作方法
windows·7-zip
池央10 小时前
Windows本地部署Qwen3.8实战:LM Studio、Cherry Studio、远程API与Token鉴权
windows
泡海椒1 天前
JQuick-SQL 快速开始:注册内存表并执行查询
数据库·windows·sql
钱栈up1 天前
耳机音效不对,我顺手查了系统更新,结果挖出个崩溃了整天的服务
windows·shell
xiao77mwq1 天前
Wireshark 在 Windows 上没法按进程抓包,我补了一条路
windows
Helix2501 天前
MDT自动化部署实战:构建企业级Windows批量装机与PXE网络引导环境
windows·mdt自动化部署·wds网络启动·pxe引导·windows批量装机·任务序列·无人值守安装
学IT的周星星1 天前
记忆系统:让 Agent 记住你是谁、上次聊到哪
运维·服务器·人工智能·windows·大模型·llm·agent
撞强1 天前
Windows 上从零开始:Obsidian + Copilot(Icompify)+ 客户洞察实战 · 图文指南
windows·copilot·obsidian·icompify