MyBatis中动态SQL语句完成多条件查询

choose(when otherwise)相当于Java中的switch语句,通常when和otherwise一起使用。

where:简化SQL语句中的where条件。

set 解决SQL语句中跟新语句

我们课已通过几个例子来看一下这几个元素的运用场景:

if:

<select id="queryEmp"  resultType="cn.test.entity.Emp">
          select * from emp where 1=1
          <if test="deptNo!=null">
          and deptno=#{deptNO}
          </if>
          <if test="deptName!=null">
          and deptno=#{deptName}
          </if>
          </select>

注:<if test="deptNo!=null">中 的deptNo是指实体类中的属性或字段;

choose

<select id="queryEmp"  resultType="cn.test.entity.Emp">
          select * from emp where 1=1
          <choose>
          <when test="deptNo!=null">
          and deptno=#{deptNo}
          </when>
          <when test="deptName!=null">
          and deptname=#{deptName}
          </when>
          <otherwise>
          and personnum>#{personNum}
          </otherwise>
          </choose>
          </select>

注:上面也说了,choose相当于Java中的switch语句;当第一个when满足时;就只执行第一个when中的条件。当when中的条件都不满足时;就会执行默认的的;也就是otherwise中的语句。

where

<select id="queryEmp"  resultType="cn.test.entity.Emp">
          select * from emp 
          <where>
          <if test="deptNo!=null">
          and deptno=#{deptNO}
          </if>
          <if test="deptName!=null">
          and deptno=#{deptName}
          </if>
          </where>
          </select>

: where下面第一个if语句中以and开头,也可以省略第一个and ,如果第一个if语句中有and;mybatis会将第一个and忽略。

 

set

  <update id="updateEmp" parameterType="cn.test.entity.Emp" flushCache="true">
          update emp 
          <set>
          <if test="empName!=null">empname=#{empName},</if>
          <if test="job!=null">job=#{job}</if>
          </set>
          where empno=#{empNo}
          </update>

 

in:

<select id="dynamicForeachTest" resultType="Blog">  

select * from t_blog where id in  

     <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  

            #{item}  

        </foreach>  

</select>

 

测试代码:

  1. @Test  
  2. public void dynamicForeachTest() {  
  3. SqlSession session = Util.getSqlSessionFactory().openSession();  
  4. BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
  5. List<Integer> ids = new ArrayList<Integer>();  
  6. ids.add(1);  
  7. ids.add(3);  
  8. ids.add(6);  
  9. List<Blog> blogs = blogMapper.dynamicForeachTest(ids);  
  10. for (Blog blog : blogs)  
  11. System.out.println(blog);  
  12. session.close();  
  13. }   

 

:  在mybatis中的SQL语句结尾不能加“;”,这样会导致mybatis无法识别字符;导致SQL语句的语法错误;出现 java.sql.SQLSyntaxErrorException:ORA-00911: 无效字符的错误。的异常。

转载于:https://www.cnblogs.com/jbml-154312/p/7799002.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值