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>

测试代码:

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

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


 上一篇
SSM框架实现xml导出并在客户端下载的三种方式 SSM框架实现xml导出并在客户端下载的三种方式
1.使用Document创建节点 // 创建xml Document document = DocumentHelper.createDocument(); //创建节点 Element elements = document.addE
2019-01-20
下一篇 
Java中Date与String的相互转换 Java中Date与String的相互转换
我们在注册网站的时候,往往需要填写个人信息,如姓名,年龄,出生日期等,在页面上的出生日期的值传递到后台的时候是一个字符串,而我们存入数据库的时候确需要一个日期类型,反过来,在页面上显示的时候,需要从数据库获取出生日期,此时该类型为日期类型,
2019-01-20
  目录