mybatis条件语句中带数组参数的处理
这篇文章主要介绍了mybatis条件语句中带数组参数的处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
目录
mybatis条件语句中带数组参数
这里给出一个示例
这里有必要说明的是foreach标签中的collection属性
mybatis多参数传递(其中包括数组)
mapper接口
mapper.xml的配置
mybatis条件语句中带数组参数
如题,在mybatis编写sql语句的时候,可能会遇到in这样的关键字,我们知道in后面需要接上('a','b','c')这样的一个结构。它像一个数组,但是是用括号()包裹的,参数之间还有逗号隔开。
这里因为数组参数是变量,直接通过拼接的方式不可行。
这里需要一个标签foreach,标签可以有item,collection,open,close,separator等属性,分别表示变量,变量集合,开始符号,结束符号,分隔符。
这里给出一个示例
定义返回对象
1 2 3 4 5 | < 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语句
1 2 3 4 5 6 7 | < 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方法:
1 2 3 4 5 6 7 8 9 | 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接口
1 | public void batchDelete( @Param (value = "activityId" ) Integer activityId, @Param (value = "userIds" ) Integer[] userIds); |
mapper.xml的配置
1 2 3 4 5 6 7 | < 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 > |
以上为个人经验,希望能给大家一个参考
原文链接:https://blog.csdn.net/feinifi/article/details/119668572