mybatis条件语句中带数组参数的处理

2022-07-21,,,,

目录
  • mybatis条件语句中带数组参数
    • 这里给出一个示例
    • 这里有必要说明的是foreach标签中的collection属性
  • mybatis多参数传递(其中包括数组)
    • mapper接口
    • mapper.xml的配置

mybatis条件语句中带数组参数

如题,在mybatis编写sql语句的时候,可能会遇到in这样的关键字,我们知道in后面需要接上('a','b','c')这样的一个结构。它像一个数组,但是是用括号()包裹的,参数之间还有逗号隔开。

这里因为数组参数是变量,直接通过拼接的方式不可行。

这里需要一个标签foreach,标签可以有item,collection,open,close,separator等属性,分别表示变量,变量集合,开始符号,结束符号,分隔符。

这里给出一个示例

定义返回对象

<resultmap type="com.xxx.springmybatis.domain.user" id="userresult">
  <id column="id" jdbctype="bigint" property="id"/>
  <result column="name" jdbctype="varchar" property="name"/>
  <result column="email" jdbctype="varchar" property="email"/>
</resultmap>

编写sql语句

<select id="findbyids" resultmap="userresult" parametertype="list">
     select * from users
     where id in
     <foreach collection="list" item="id" open="(" close=")" separator=",">
      #{id,jdbctype=bigint}
     </foreach>
</select>

定义dao方法:

package com.xxx.springmybatis.dao;
import java.util.list;
import com.xxx.springmybatis.domain.user;
public interface usermapper {
    user getbyid(integer id);
    user getbyname(string name);
    void save(user user);    
    list<user> findbyids(list<integer> ids);
}

以上的示例,是通过id数组来查询对应的用户集合。我们传入的用户id,最终在sql中会通过拼接的方式组成where id in (3,4)的条件。

如下所示,如果要查询id为3,4的用户,那么打印的sql语句可以看出拼接的样子:

这里有必要说明的是foreach标签中的collection属性

1、list集合,默认使用list代表入参,数组,默认使用array作为入参。

2、如果传入的参数是一个对象,对象user有个属性list ids,那么就使用ids作为入参。

3、如果接口声明的地方通过注解@param("xx")指定了入参,那么list,array这种默认的参数就失效,这时候需要指定xx为入参。

本例中因为使用的是list集合传入,所以默认就使用了list作为collection入参的键。

mybatis多参数传递(其中包括数组)

mapper接口

public void batchdelete(@param(value = "activityid") integer activityid, @param(value = "userids") integer[] userids);

mapper.xml的配置

<insert id="batchdelete">
     delete from t_act_users where activity_id = #{activityid}
     and user_id in
     <foreach collection="userids" item="item" index="index" open="(" separator="," close=")">
            #{item}
     </foreach>
</insert>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《mybatis条件语句中带数组参数的处理.doc》

下载本文的Word格式文档,以方便收藏与打印。