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

查看:2313
本文介绍了如何将整数数组传递给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

请提出任何建议

推荐答案

关于动态SQL的myBatis用户指南有一个如何使用的示例用于构建查询字符串的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天全站免登陆