mybatis动态SQL之foreach标签

mybatis动态SQL之foreach标签

需求:传入多个 id 查询用户信息,用下边两个 sql 实现:

SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)

SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)

这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。

这样我们将如何进行参数的传递?

1、实体类

public class QueryVo implements Serializable {
    private List<Integer> ids;
    
	public List<Integer> getIds() {
		return ids; 
    }
    
	public void setIds(List<Integer> ids) {
		this.ids = ids; 
    } 
}

2、持久层接口

/**
* 根据 id 集合查询用户
* @param vo
* @return
*/
List<User> findInIds(QueryVo vo);

3、映射文件

<!-- 查询所有用户在 id 的集合之中 -->
<select id="findInIds" resultType="user" parameterType="queryvo">
    <!-- select * from user where id in (1,2,3,4,5); -->
	select * from user 
    <where> 
        <if test="ids != null and ids.size() > 0"> 
            <foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
		#{uid}
	    </foreach>
	</if>
    </where>
</select>

SQL 语句:

select 字段 from user where id in (?)

foreach标签用于遍历集合,它的属性

  • collection:代表要遍历的集合元素,注意编写时不要写#{}
  • open:代表语句的开始部分
  • close:代表结束部分
  • item:代表遍历集合的每个元素,生成的变量名
  • sperator:代表分隔符
记得快乐
原文地址:https://www.cnblogs.com/Y-wee/p/13835423.html