需求:传入多个 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:代表分隔符
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
您可能感兴趣的文章:
- 创建Gradle工程出现Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradleXX'.问题解决
- spring boot 错误:Check your ViewResolver setup
- java实现判断一个整数是几位数,并按照逆序输出
- Please, configure Web Facet first!idea报这错的解决办法!!
- SpringBoot 2.0 报错: Failed to configure a DataSource: 'url' attribute is not specified and no embe
- [异常处理1]Error occurred during initialization of boot layer
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论