转自:http://www.blogjava.net/Steven-bot/articles/363460.html

动态SQL语句--mybatis

动态SQL语句
        有些时候,sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空 时,是查出全部的信息。这是我们可以使用动态sql,增加一个判断,当参数不符合要求的时候,我们可以不去判断此查询条件。
        下文均采用mysql语法和函数(例如字符串链接函数CONCAT)。

源代码http://limingnihao.javaeye.com/admin/blogs/782190
3.1 if标签
 一个很普通的查询:
Xml代码  
<!-- 查询学生list,like姓名 -->   
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST     
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
</select>   
<!-- 查询学生list,like姓名 -->
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST 
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
</select>
但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。
修改为:
Xml代码  
<!-- 查询学生list,like姓名 -->   
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <if test="studentName!=null and studentName!='' ">   
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
    </if>   
</select>   
<!-- 查询学生list,like姓名 -->
<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
 <if test="studentName!=null and studentName!='' ">
  WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
 </if>
</select>
 此时,当studentName的值为null或’’的时候,我们并不进行where条件的判断,所以当studentName值为null或’’值,不附带这个条件,所以查询结果是全部。
由于参数是Java的实体类,所以我们可以把所有条件都附加上,使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。

   代码中的where标签,请参考3.2.1.
Xml代码  
<!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->   
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <where>   
        <if test="studentName!=null and studentName!='' ">   
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
        </if>   
        <if test="studentSex!= null and studentSex!= '' ">   
            AND ST.STUDENT_SEX = #{studentSex}    
        </if>   
        <if test="studentBirthday!=null">   
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday}    
        </if>   
        <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">   
            AND ST.CLASS_ID = #{classEntity.classID}    
        </if>   
    </where>   
</select>   
<!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
 <where>
  <if test="studentName!=null and studentName!='' ">
   ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
  </if>
  <if test="studentSex!= null and studentSex!= '' ">
   AND ST.STUDENT_SEX = #{studentSex}
  </if>
  <if test="studentBirthday!=null">
    AND ST.STUDENT_BIRTHDAY = #{studentBirthday}
  </if>
  <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">
   AND ST.CLASS_ID = #{classEntity.classID}
  </if>
 </where>
</select>
查询,姓名中有‘李’,男,生日在‘1985-05-28’,班级在‘20000002’的学生。
Java代码  
StudentEntity entity = new StudentEntity();    
entity.setStudentName("李");    
entity.setStudentSex("男");    
entity.setStudentBirthday(StringUtil.parse("1985-05-28"));    
entity.setClassEntity(classMapper.getClassByID("20000002"));    
List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);    
for( StudentEntity entityTemp : studentList){    
    System.out.println(entityTemp.toString());    
}   
StudentEntity entity = new StudentEntity();
entity.setStudentName("李");
entity.setStudentSex("男");
entity.setStudentBirthday(StringUtil.parse("1985-05-28"));
entity.setClassEntity(classMapper.getClassByID("20000002"));
List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);
for( StudentEntity entityTemp : studentList){
 System.out.println(entityTemp.toString());
}
3.2 where、set、trim标签
3.2.1 where
当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:
Xml代码  
<!-- 查询学生list,like姓名,=性别 -->   
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
        WHERE    
        <if test="studentName!=null and studentName!='' ">   
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
        </if>   
        <if test="studentSex!= null and studentSex!= '' ">   
            AND ST.STUDENT_SEX = #{studentSex}    
        </if>   
</select>   
<!-- 查询学生list,like姓名,=性别 -->
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
  WHERE
  <if test="studentName!=null and studentName!='' ">
   ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
  </if>
  <if test="studentSex!= null and studentSex!= '' ">
   AND ST.STUDENT_SEX = #{studentSex}
  </if>
</select>
 如果上面例子,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
 这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
 上面例子修改为:
Xml代码  
<!-- 查询学生list,like姓名,=性别 -->   
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <where>   
        <if test="studentName!=null and studentName!='' ">   
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
        </if>   
        <if test="studentSex!= null and studentSex!= '' ">   
            AND ST.STUDENT_SEX = #{studentSex}    
        </if>   
    </where>   
</select>   
<!-- 查询学生list,like姓名,=性别 -->
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
 <where>
  <if test="studentName!=null and studentName!='' ">
   ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
  </if>
  <if test="studentSex!= null and studentSex!= '' ">
   AND ST.STUDENT_SEX = #{studentSex}
  </if>
 </where>
</select>
3.2.2 set
当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:
Xml代码  
<!-- 更新学生信息 -->   
<update id="updateStudent" parameterType="StudentEntity">   
    UPDATE STUDENT_TBL    
       SET STUDENT_TBL.STUDENT_NAME = #{studentName},    
           STUDENT_TBL.STUDENT_SEX = #{studentSex},    
           STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},    
           STUDENT_TBL.CLASS_ID = #{classEntity.classID}    
     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update>   
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="StudentEntity">
 UPDATE STUDENT_TBL
    SET STUDENT_TBL.STUDENT_NAME = #{studentName},
        STUDENT_TBL.STUDENT_SEX = #{studentSex},
        STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
        STUDENT_TBL.CLASS_ID = #{classEntity.classID}
  WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
</update>
使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:
Xml代码  
<!-- 更新学生信息 -->   
<update id="updateStudent" parameterType="StudentEntity">   
    UPDATE STUDENT_TBL    
    <set>   
        <if test="studentName!=null and studentName!='' ">   
            STUDENT_TBL.STUDENT_NAME = #{studentName},    
        </if>   
        <if test="studentSex!=null and studentSex!='' ">   
            STUDENT_TBL.STUDENT_SEX = #{studentSex},    
        </if>   
        <if test="studentBirthday!=null ">   
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},    
        </if>   
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">   
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}    
        </if>   
    </set>   
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update>   
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="StudentEntity">
 UPDATE STUDENT_TBL
 <set>
  <if test="studentName!=null and studentName!='' ">
   STUDENT_TBL.STUDENT_NAME = #{studentName},
  </if>
  <if test="studentSex!=null and studentSex!='' ">
   STUDENT_TBL.STUDENT_SEX = #{studentSex},
  </if>
  <if test="studentBirthday!=null ">
   STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
  </if>
  <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">
   STUDENT_TBL.CLASS_ID = #{classEntity.classID}
  </if>
 </set>
 WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
</update>
3.2.3 trim
 trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。

 where例子的等效trim语句:
Xml代码  
<!-- 查询学生list,like姓名,=性别 -->   
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <trim prefix="WHERE" prefixOverrides="AND|OR">   
        <if test="studentName!=null and studentName!='' ">   
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
        </if>   
        <if test="studentSex!= null and studentSex!= '' ">   
            AND ST.STUDENT_SEX = #{studentSex}    
        </if>   
    </trim>   
</select>   
<!-- 查询学生list,like姓名,=性别 -->
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
 <trim prefix="WHERE" prefixOverrides="AND|OR">
  <if test="studentName!=null and studentName!='' ">
   ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
  </if>
  <if test="studentSex!= null and studentSex!= '' ">
   AND ST.STUDENT_SEX = #{studentSex}
  </if>
 </trim>
</select>
set例子的等效trim语句:
Xml代码  
<!-- 更新学生信息 -->   
<update id="updateStudent" parameterType="StudentEntity">   
    UPDATE STUDENT_TBL    
    <trim prefix="SET" suffixOverrides=",">   
        <if test="studentName!=null and studentName!='' ">   
            STUDENT_TBL.STUDENT_NAME = #{studentName},    
        </if>   
        <if test="studentSex!=null and studentSex!='' ">   
            STUDENT_TBL.STUDENT_SEX = #{studentSex},    
        </if>   
        <if test="studentBirthday!=null ">   
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},    
        </if>   
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">   
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}    
        </if>   
    </trim>   
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};    
</update>   
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="StudentEntity">
 UPDATE STUDENT_TBL
 <trim prefix="SET" suffixOverrides=",">
  <if test="studentName!=null and studentName!='' ">
   STUDENT_TBL.STUDENT_NAME = #{studentName},
  </if>
  <if test="studentSex!=null and studentSex!='' ">
   STUDENT_TBL.STUDENT_SEX = #{studentSex},
  </if>
  <if test="studentBirthday!=null ">
   STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
  </if>
  <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">
   STUDENT_TBL.CLASS_ID = #{classEntity.classID}
  </if>
 </trim>
 WHERE STUDENT_TBL.STUDENT_ID = #{studentID};
</update>
3.3 choose (when, otherwise)
         有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
         if是与(and)的关系,而choose是或(or)的关系。

         例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:
Xml代码  
<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->   
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">   
    SELECT * from STUDENT_TBL ST    
    <where>   
        <choose>   
            <when test="studentName!=null and studentName!='' ">   
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')    
            </when>   
            <when test="studentSex!= null and studentSex!= '' ">   
                    AND ST.STUDENT_SEX = #{studentSex}    
            </when>   
            <when test="studentBirthday!=null">   
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}    
            </when>   
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">   
                AND ST.CLASS_ID = #{classEntity.classID}    
            </when>   
            <otherwise>   
                    
            </otherwise>   
        </choose>   
    </where>   
</select>   
<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">
 SELECT * from STUDENT_TBL ST
 <where>
  <choose>
   <when test="studentName!=null and studentName!='' ">
     ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
   </when>
   <when test="studentSex!= null and studentSex!= '' ">
     AND ST.STUDENT_SEX = #{studentSex}
   </when>
   <when test="studentBirthday!=null">
    AND ST.STUDENT_BIRTHDAY = #{studentBirthday}
   </when>
   <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">
    AND ST.CLASS_ID = #{classEntity.classID}
   </when>
   <otherwise>
    
   </otherwise>
  </choose>
 </where>
</select>
3.4 foreach
对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。
3.4.1参数为list实例的写法:
SQL写法:
Xml代码  
<select id="getStudentListByClassIDs" resultMap="studentResultMap">   
    SELECT * FROM STUDENT_TBL ST    
     WHERE ST.CLASS_ID IN     
     <foreach collection="list" item="classList"  open="(" separator="," close=")">   
        #{classList}    
     </foreach>       
</select>   
<select id="getStudentListByClassIDs" resultMap="studentResultMap">
 SELECT * FROM STUDENT_TBL ST
  WHERE ST.CLASS_ID IN 
  <foreach collection="list" item="classList"  open="(" separator="," close=")">
   #{classList}
  </foreach> 
</select>
接口的方法声明:
Java代码  
public List<StudentEntity> getStudentListByClassIDs(List<String> classList);   
public List<StudentEntity> getStudentListByClassIDs(List<String> classList); 测试代码,查询学生中,在20000002、20000003这两个班级的学生:
Java代码  
List<String> classList = new ArrayList<String>();    
classList.add("20000002");    
classList.add("20000003");    
   
List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);    
for( StudentEntity entityTemp : studentList){    
    System.out.println(entityTemp.toString());    
}   
List<String> classList = new ArrayList<String>();
classList.add("20000002");
classList.add("20000003");
List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);
for( StudentEntity entityTemp : studentList){
 System.out.println(entityTemp.toString());
}
3.4.2参数为Array实例的写法:
SQL语句:
Xml代码  
<select id="getStudentListByClassIDs" resultMap="studentResultMap">   
    SELECT * FROM STUDENT_TBL ST    
     WHERE ST.CLASS_ID IN     
     <foreach collection="array" item="ids"  open="(" separator="," close=")">   
        #{ids}    
     </foreach>   
</select>   
<select id="getStudentListByClassIDs" resultMap="studentResultMap">
 SELECT * FROM STUDENT_TBL ST
  WHERE ST.CLASS_ID IN 
  <foreach collection="array" item="ids"  open="(" separator="," close=")">
   #{ids}
  </foreach>
</select>
接口的方法声明:
Java代码  
public List<StudentEntity> getStudentListByClassIDs(String[] ids);   
public List<StudentEntity> getStudentListByClassIDs(String[] ids);测试代码,查询学生中,在20000002、20000003这两个班级的学生:
Java代码  
String[] ids = new String[2];    
ids[0] = "20000002";    
ids[1] = "20000003";    
List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);    
for( StudentEntity entityTemp : studentList){    
    System.out.println(entityTemp.toString());    
}  

转载于:https://blog.51cto.com/ibird/1010069

动态SQL语句--mybatis相关推荐

  1. Mybatis Plus 是如何实现动态 SQL 语句的?原理你懂吗?

    作者 | 稻草江南 来源 | https://juejin.cn/post/6883081187103866894 Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,那么它是怎么 ...

  2. Mybatis映射文件动态SQL语句-01

    因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句, UserMapper.xml <?xml version=" ...

  3. MyBatis——动态SQL语句——if标签和where标签复合使用

    功能需求 根据性别和名字查询用户 官方文档 MyBatis--动态 SQL SQL语句 SELECT id, username, birthday, sex, address FROM `user` ...

  4. Mybatis 动态Sql语句《常用》

    MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...

  5. 【转】mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

    转自:除非申明,文章均为一号门原创,转载请注明本文地址,谢谢! 转载地址:http://blog.csdn.net/kutejava/article/details/9164353#t5 1. if ...

  6. mybatis动态SQL语句

    三.动态SQL语句 有些时候,sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息.这是我们可以使 ...

  7. MyBatis学习 之 三、动态SQL语句

    2019独角兽企业重金招聘Python工程师标准>>> 有些时候,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空,此时查询出的结果很可能是空的, ...

  8. MyBatis学习总结(11)——MyBatis动态Sql语句

    MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...

  9. java day55【 Mybatis 连接池与事务深入 、 Mybatis 的动态 SQL 语句、 Mybatis 多表查询之一对多 、 Mybatis 多表查询之多对多】...

    第1章 Mybatis 连接池与事务深入 1.1 Mybatis 的连接池技术 1.1.1 Mybatis 连接池的分类 1.1.2 Mybatis 中数据源的配置 1.1.3 Mybatis 中 D ...

最新文章

  1. python set list str转换
  2. Lotus Notes基础知识
  3. 【机器学习】深入理解CatBoost
  4. core和node开发小程序_node+微信小程序实现商城案例
  5. 点这里,关注计算机视觉技术最前沿~
  6. 算法笔记_100:蓝桥杯练习 算法提高 三个整数的排序(Java)
  7. 时间格式化及操作(moment.js篇)
  8. SSM中使用注解方式调用输入输出参数存储过程,输入参数为javabean方式,Boolean类型对应TINYINT类型
  9. Vue:带参数函数在传递参数的同时传递事件对象
  10. 代码开源许可证 区别 Apache MIT GPL
  11. 对初学者来说,Python难度不低于其他语言
  12. 电脑分屏没有声音_电脑用HDMI线分屏后,耳机或音箱没声音之完美解决!
  13. 硬链接(hard link)与软链接(soft link/symbolic link)
  14. 解决 Refused to display in a frame because it set 'X-Frame-Options' to 'deny'.问题
  15. 利用JAVA求定积分
  16. “计算机无法访问,您可能没有权限使用网络资源”解决方法
  17. 1,标准差的计算 2,标准分数z-score
  18. 第四章第6节水管工游戏
  19. Android热修复(1):热修复的介绍和原理解析
  20. CV学习笔记-VGG

热门文章

  1. hexo的next主题个性化教程 打造炫酷网站
  2. .NET英文技术文章导读(2017-02-09)
  3. C#发送邮件异常:根据验证过程,远程证书无效
  4. lvm 逻辑卷 和 网络管理
  5. Nginx-location常用配置
  6. Docker基础之九: 管理容器的数据
  7. IE下Ajax 提交中文乱码问题
  8. android permission 访问权限大全
  9. java使用ssh连接Linux并执行命令
  10. 如何通过人工智能“避开”内容安全的“坑”?