mybatis动态SQL语句

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

三、动态SQL语句

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

1 if标签

<!-- 查询学生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或等于空字符串,我们就不进行此条件的判断。

修改为:

<!-- 查询学生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中判断。

<!-- 查询学生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>  

2 where、set、trim标签

2.1 where

    当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:

  1. <!-- 查询学生list,like姓名,=性别 -->  
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4.         WHERE   
  5.         <if test="studentName!=null and studentName!='' ">  
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   
  7.         </if>  
  8.         <if test="studentSex!= null and studentSex!= '' ">  
  9.             AND ST.STUDENT_SEX = #{studentSex}   
  10.         </if>  
  11. </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>  

2.2 set

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:

<!-- 更新学生信息 -->  
<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则不进行更新,而是保持数据库原值。如下示例:

<!-- 更新学生信息 -->  
<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>

2.3 trim

 trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。


 where例子的等效trim语句:

<!-- 查询学生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语句:

<!-- 更新学生信息 -->  
<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 choose (when, otherwise)

         有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
         if是与(and)的关系,而choose是或(or)的关系。


         例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:

<!-- 查询学生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>  

4 foreach

对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。

foreach属性

属性 描述
item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection 要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键
当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果User有属性List ids。入参是User对象,那么这个collection = "ids"
如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素做循环。
该参数为必选。
separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
close foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

4.1参数为list实例的写法:

SQL写法:

<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> 

接口的方法声明:

  1. public List<StudentEntity> getStudentListByClassIDs(List<String> classList);  


  1. List<String> classList = new ArrayList<String>();   
  2. classList.add("20000002");   
  3. classList.add("20000003");   
  4.   
  5. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);   
  6. for( StudentEntity entityTemp : studentList){   
  7.     System.out.println(entityTemp.toString());   

4.2参数为Array实例的写法:

 

SQL语句:

<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代码  复制代码  收藏代码
  1. public List<StudentEntity> getStudentListByClassIDs(String[] ids);  

测试代码,查询学生中,在20000002、20000003这两个班级的学生:

Java代码  复制代码  收藏代码
  1. String[] ids = new String[2];   
  2. ids[0] = "20000002";   
  3. ids[1] = "20000003";   
  4. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);   
  5. for( StudentEntity entityTemp : studentList){   
  6.     System.out.println(entityTemp.toString());   
  7. }


相关文章
|
2月前
|
SQL Java 测试技术
3、Mybatis-Plus 自定义sql语句
这篇文章介绍了如何在Mybatis-Plus框架中使用自定义SQL语句进行数据库操作。内容包括文档结构、编写mapper文件、mapper.xml文件的解释说明、在mapper接口中定义方法、在mapper.xml文件中实现接口方法的SQL语句,以及如何在单元测试中测试自定义的SQL语句,并展示了测试结果。
3、Mybatis-Plus 自定义sql语句
|
9天前
|
SQL XML Java
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
文章介绍了MyBatis中动态SQL的用法,包括if、choose、where、set和trim标签,以及foreach标签的详细使用。通过实际代码示例,展示了如何根据条件动态构建查询、更新和批量插入操作的SQL语句。
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
|
2月前
|
SQL Java 数据库连接
Mybatis系列之 Error parsing SQL Mapper Configuration. Could not find resource com/zyz/mybatis/mapper/
文章讲述了在使用Mybatis时遇到的资源文件找不到的问题,并提供了通过修改Maven配置来解决资源文件编译到target目录下的方法。
Mybatis系列之 Error parsing SQL Mapper Configuration. Could not find resource com/zyz/mybatis/mapper/
|
1月前
|
SQL XML Java
mybatis :sqlmapconfig.xml配置 ++++Mapper XML 文件(sql/insert/delete/update/select)(增删改查)用法
当然,这些仅是MyBatis功能的初步介绍。MyBatis还提供了高级特性,如动态SQL、类型处理器、插件等,可以进一步提供对数据库交互的强大支持和灵活性。希望上述内容对您理解MyBatis的基本操作有所帮助。在实际使用中,您可能还需要根据具体的业务要求调整和优化SQL语句和配置。
30 1
|
2月前
|
SQL Java 数据库连接
Mybatis系列之 动态SQL
文章详细介绍了Mybatis中的动态SQL用法,包括`<if>`、`<choose>`、`<when>`、`<otherwise>`、`<trim>`和`<foreach>`等元素的应用,并通过实际代码示例展示了如何根据不同条件动态生成SQL语句。
|
2月前
|
SQL Java 关系型数据库
SpringBoot 系列之 MyBatis输出SQL日志
这篇文章介绍了如何在SpringBoot项目中通过MyBatis配置输出SQL日志,具体方法是在`application.yml`或`application.properties`中设置MyBatis的日志实现为`org.apache.ibatis.logging.stdout.StdOutImpl`来直接在控制台打印SQL日志。
SpringBoot 系列之 MyBatis输出SQL日志
|
2月前
|
SQL 关系型数据库 MySQL
解决:Mybatis-plus向数据库插入数据的时候 报You have an error in your SQL syntax
该博客文章讨论了在使用Mybatis-Plus向数据库插入数据时遇到的一个常见问题:SQL语法错误。作者发现错误是由于数据库字段中使用了MySQL的关键字,导致SQL语句执行失败。解决方法是将这些关键字替换为其他字段名称,以避免语法错误。文章通过截图展示了具体的操作步骤。
|
3月前
|
SQL Java 数据库连接
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
60 3
|
3月前
|
SQL Java 数据库连接
mybatis动态SQL常用语法总结
MyBatis 使用 OGNL 表达式语言处理动态SQL,如 `if` 标签进行条件判断,`choose`、`when`、`otherwise` 实现多条件选择,`where`、`set` 管理SQL关键字,`trim` 提供通用修剪功能,`foreach` 遍历集合数据。`sql` 和 `include` 用于代码重用,`selectKey` 处理插入后的返回值。参数传递支持匿名、具名、列表、Map、Java Bean和JSON方式。注意SQL转义及使用合适的jdbcType映射Java类型。
73 7
|
21天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
下一篇
无影云桌面