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

12 篇文章 0 订阅

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值