如何在 MyBatis 中将整数数组传递给 IN 子句 [英] How to pass an Integer Array to IN clause in MyBatis

查看:49
本文介绍了如何在 MyBatis 中将整数数组传递给 IN 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Mybatis 中有一个包含 IN 子句的查询,它基本上是一组 Id(整数)

There is a query in my Mybatis containing an IN clause which is basically a set of Id's ( Integers)

我现在被困在如何将整数数组传递给这个 IN 子句,以便它提取正确的记录.尝试通过将包含 ID 的字符串传递给 IN 子句,但这没有按预期工作.

I am now stuck on how can I pass an Integer array to this IN clause so that it pulls up the proper records.Tried by passing a String containing the ID's to the IN clause , but this did not work as expected.

下面的代码示例

Mybatis 使用注解的方法

Mybatis Method using Annotations

@Select(SEL_QUERY)
    @Results(value = {@Result(property="id",column="ID")})
    List<Integer> getIds(@Param("usrIds") Integer[] usrIds);

查询

select distinct ID from table a where a.id in ( #{usrIds} )

方法调用

Integer[] arr = new Integer[2];
arr[0] = 1;
arr[1] = 2;

mapper.getIds(arr)

这不起作用,Mybatis在调用mapper方法时抛出错误

This is not working , Mybatis throws an error when I call the mapper method

任何建议请

推荐答案

myBatis动态 SQL 用户指南 有一个关于如何使用 foreach 循环构建查询字符串的示例,该字符串适用于列表和数组.

The myBatis User Guide on Dynamic SQL has an example on how to use a foreach loop to build the query string, which works for lists and arrays.

在发布 3.2 之前,您必须使用 xml 配置来使用动态 sql,对于较新的版本,它也应该可以使用 注解中的动态sql.

Prior to release 3.2 you had to use xml configuration to use dynamic sql, with newer versions it should also be possible to use dynamic sql in annotations.

<select id="selectPostIn" resultType="domain.blog.Post">
    SELECT *
    FROM POST P
    WHERE ID in
    <foreach item="item" index="index" collection="list"
             open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

这篇关于如何在 MyBatis 中将整数数组传递给 IN 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆