首先查询对象包含一个集合属性,定义为ids如下:
package com.ajin.mybatis.model;
import java.util.List;
/**
* Created by ajin on 16-12-16.
*/
public class StudentVo {
private Student student;
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
然后修改之前编写的sql片段:
<!--sql片段
id:sql片段的唯一标识
经验:一般基于单表地定义sql片段,这样可重用性比较高,sql片段中不要包含 where
第一步:定义sql片段
第二步:引用sql片段
-->
<sql id="select_student">
<if test="student!=null">
<if test="student.sname!=null and student.sname!=''">
and s.sname=#{student.sname}
</if>
<if test="student.ssex!=null and student.ssex!=''">
and s.ssex=#{student.ssex}
</if>
<if test="ids !=null">
<!-- 使用foreach来遍历查询条件中的集合属性
collection指定查询对象中的集合属性:
item:遍历对象中
open:开始时拼接字符串
close:结束拼接字符串
separator:遍历中间需要拼接的串
-->
<foreach collection="ids" item="s_id" open="and (" close=")" separator="or">
id=#{s_id}
</foreach>
</if>
</if>
</sql>
最后来测试我们集合查询结果如下:
@Test
public void selectStudentMul() throws Exception {
StudentVo studentVo= new StudentVo();
Student student = new Student();
student.setSname("zcj");
student.setSsex("female");
List<Integer> ids = new ArrayList<Integer>();
ids.add(3);
ids.add(4);
studentVo.setIds(ids);
studentVo.setStudent(student);
SqlSession sqlSession = sqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list=studentMapper.selectStudentMul(studentVo);
System.out.print(list);
}finally {
sqlSession.close();
}
}
可以看到我们在ids集合中增加了两个id值,生成的sql查询语句如下:
DEBUG [main] - ==> Preparing: select * from student s WHERE s.sname=? and s.ssex=? and ( id=? or id=? )
DEBUG [main] - ==> Parameters: zcj(String), female(String), 3(Integer), 4(Integer)
DEBUG [main] - <== Total: 2