Python 官方文档:入门教程 => 点击学习
目录mybatis条件语句中带数组参数这里给出一个示例这里有必要说明的是foreach标签中的collection属性mybatis多参数传递(其中包括数组)mapper接口mapp
如题,在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语句可以看出拼接的样子:
1、List集合,默认使用list代表入参,数组,默认使用array作为入参。
2、如果传入的参数是一个对象,对象User有个属性List ids,那么就使用ids作为入参。
3、如果接口声明的地方通过注解@Param("xx")指定了入参,那么list,array这种默认的参数就失效,这时候需要指定xx为入参。
本例中因为使用的是List集合传入,所以默认就使用了list作为collection入参的键。
public void batchDelete(@Param(value = "activityId") Integer activityId, @Param(value = "userIds") Integer[] userIds);
<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>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: mybatis条件语句中带数组参数的处理
本文链接: https://www.lsjlt.com/news/135378.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0