zoukankan      html  css  js  c++  java
  • Mybatis动态查询语句

     

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

    标签: mybatis动态SQL多条件查询java.sql.SQLSyntaxEr
     分类:

    一看这标题,我都感觉到是mybatis在动态SQL语句中的多条件查询是多么的强大,不仅让我们用SQL语句完成了对数据库的操作;还通过一些条件选择语句让我们SQL的多条件、动态查询更加容易、简洁、直观。

    mybatis中用于实现动态SQL的元素有: if:用if实现条件的选择,用于定义where的字句的条件。

    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>

     

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

  • 相关阅读:
    二叉树--转换二叉树(leetcode 108,leetcode 109)
    二叉树--层序遍历(leetcode 102
    二叉树--对称二叉树(leetcode 101
    数据库事务隔离
    二叉树--后序遍历的递归和非递归(leetcode 145
    二叉树--中序遍历的递归和非递归(leetcode 94
    二叉树--先序遍历的递归和非递归(leetcode 144
    链表--排序链表(leetcode 148
    接口的调用
    查锁表以及杀进程
  • 原文地址:https://www.cnblogs.com/yueguanguanyun/p/7731351.html
Copyright © 2011-2022 走看看