当前位置: 移动技术网 > IT编程>开发语言>Java > Mybatis动态SQL foreach标签用法实例

Mybatis动态SQL foreach标签用法实例

2020年10月26日  | 移动技术网IT编程  | 我要评论
需求:传入多个 id 查询用户信息,用下边两个 sql 实现:select * from users where username like '%张%' and (id =10 or id =89 o

需求:传入多个 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:代表分隔符

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网