ssm框架学习---mybatis中动态sql中的foreach片段

首先查询对象包含一个集合属性,定义为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 ids;

    public List getIds() {
        return ids;
    }

    public void setIds(List ids) {
        this.ids = ids;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }
}
然后修改之前编写的sql片段:

  
    
        
            
                and s.sname=#{student.sname}
            
            
                and s.ssex=#{student.ssex}
            
            
                
                
                    id=#{s_id}
                
            
        
    
最后来测试我们集合查询结果如下:

 @Test
    public void selectStudentMul() throws Exception {
        StudentVo studentVo= new StudentVo();
       Student student = new Student();
       student.setSname("zcj");
       student.setSsex("female");
       List ids = new ArrayList();
       ids.add(3);
       ids.add(4);
       studentVo.setIds(ids);
       studentVo.setStudent(student);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List 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


你可能感兴趣的:(SSM,Mybatis)