java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis动态SQL

Mybatis动态SQL foreach标签用法实例

作者:Y_wee

这篇文章主要介绍了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标签用于遍历集合,它的属性

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

您可能感兴趣的文章:
阅读全文