mybatis6 动态sql

1.动态SQL中的元素

动态SQL是MyBatis的强大特性之一,MyBatis3采用了功能强大的基于OGNL的表达式来完成动态SQL,它消除了之前版本中需要了解的大多数元素,使用不到原来一半的元素就能完成所需工作。

MyBatis动态SQL中的主要元素,如表1所示。

表1 MyBatis的动态SQL元素

元素说明
<if>判断语句,用于单条件分支判断
<choose>(<when>、<otherwise>)相当于Java中的switch...case...default语句,用于多条件分支判断
<where>、<trim>、<set>辅助元素,用于处理一些SQL拼装、特殊字符问题
<foreach>循环语句,常用于in语句等列举条件中
<bind>从OGNL表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询的sql中

表1列举了MyBatis动态SQL的一些主要元素,并分别对其作用进行了简要介绍。

动态sql,查询条件不确定有多少可以用HashMap来存储,也可以用一个类来封装所有可能的条件

用HashMap

优点:无需单独定义查询条件类

缺点:向HashMap中添加数据时的key要和sql语句查询时一致

用一个查询条件类

优点:在sql语句获取参数时直接使用属性名,不用担心命名不一致问题

缺点:需要单独定义一个类

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class StudentSearchCondition {
    private String gender;
//整形使用int在判断时不能用null,而用0
//使用Integer对象类型时用null
    private Integer age;
    private String name;
}
//动态sql,查询条件不确定可以用HashMap
public List<Student> searchStudent(HashMap<String,Object> params);
//动态sql,查询条件不确定也可以用一个类来封装所有可能的条件
public List<Student> searchStudent(StudentSearchCondition params);
HashMap<String,Object> params=new HashMap<>();
params.put("gender","女");
params.put("age",18);

StudentDAO studentDAO=mybatisUtils.getMapper(StudentDAO.class);

List<Student> studentList=studentDAO.searchStudent(params);

studentList.forEach(System.out::println);
StudentSearchCondition params=new StudentSearchCondition();
params.setGender("女");
params.setAge(18);
StudentDAO studentDAO=mybatisUtils.getMapper(StudentDAO.class);

List<Student> studentList=studentDAO.searchStudent(params);

studentList.forEach(System.out::println);
    <select id="searchStudent" resultMap="studentMap">
        select sid,sname,sgender,sage,scid
        from students
<!--  使用一个1=1条件拼接后面的条件,拼接都用and,如果第一个条件没有会出现空条件错误-->
        where 1=1
<!--         可以直接获取条件类的属性值,
            大于小于不要使用符号>,<,容易和标签混合,
            大于使用(&gt;),小于使用(&lt;),
            当无法判定是对象类型还是基本类型就都判断一下
-->
        <if test="gender!=null and gender!='' ">
             and sgender=#{gender}
        </if>
        <if test="age!=null and age!=0">
            and sage=#{age}
        </if>
    </select>

 

2.<if>元素可多条件组合

在MyBatis中,<if>元素是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择。

    <select id="searchStudent" resultMap="studentMap">
        select sid,sname,sgender,sage,scid
        from students
        where 1=1
<!--         可以直接获取条件类的属性值,
            大于小于不要使用符号>,<,容易和标签混合,
            大于使用(&gt;),小于使用(&lt;),
            当无法判定是对象类型还是基本类型就都判断一下
-->
        <if test="gender!=null and gender!='' ">
             and sgender=#{gender}
        </if>
        <if test="age!=null and age!=0">
            and sage=#{age}
        </if>
    </select>

3.<where>、<trim>、<foreach>元素

映射文件中编写的SQL后面都加入了“where 1=1”的条件防止直接拼接and关键字出现异常,使用where标签可以解决这个问题,<where>元素会自动判断组合条件下拼装的SQL语句,只有<where>元素内的条件成立时,才会在拼接SQL中加入where关键字,否则将不会添加;即使where之后的内容有多余的“AND”或“OR”,<where>元素也会自动将他们去除。

        <where>
            <if test="gender!=null and gender!='' ">
                and sgender=#{gender}
            </if>
            <if test="age!=null and age!=0">
                and sage=#{age}
            </if>
        </where>

<trim>元素的作用是去除一些特殊的字符串,它的prefix属性代表的是语句的前缀(这里使用where来连接后面的SQL片段),而prefixOverrides属性代表的是需要去除的哪些特殊字符串(这里定义了要去除SQL中的and或or),suffix表示最后要拼接的后缀操作(加前缀后缀,删除一些东西)

        <trim prefix="where" prefixOverrides="and | or" suffix="order by sname">
            <if test="gender!=null and gender!='' ">
                and sgender=#{gender}
            </if>
            <if test="age!=null and age!=0">
                and sage=#{age}
            </if>
        </trim>

MyBatis中已经提供了一种用于数组和集合循环遍历的方式,那就是使用<foreach>元素,<foreach>元素通常在构建IN条件语句时使用。其使用方式如下:

    //动态sql,查询年龄是18,19,20的学生
    public List<Student> searchStudentByAge(List<Integer> age);
@Test
    public void searchStudentByAge() {
        List<Integer> ages = new ArrayList<>();
        ages.add(18);
        ages.add(19);
        ages.add(20);

        StudentDAO studentDAO=mybatisUtils.getMapper(StudentDAO.class);

        List<Student> studentList=studentDAO.searchStudentByAge(ages);

        studentList.forEach(System.out::println);

    }
<select id="searchStudentByAge" resultMap="studentMap">
        select sid,sname,sgender,sage,scid
        from students
        where sage in
        <foreach collection="list" item="age" index="index"
                 open="(" separator="," close=")" >
            #{age}
        </foreach>
    </select>

在上述代码中,使用了<foreach>元素对传入的集合进行遍历并进行了动态SQL组装。关于<foreach>元素中使用的几种属性的描述具体如下:

● item:配置的是循环中当前的元素。

● index:配置的是当前元素在集合的位置下标。

● collection:配置的list是传递过来的参数类型(首字母小写),它可以是一个array、list(或collection)、Map集合的键、POJO包装类中数组或集合类型的属性名等。

● open和close:配置的是以什么符号将这些集合元素包装起来。

● separator:配置的是各个元素的间隔符。

注意:

你可以将任何可迭代对象(如列表、集合等)和任何的字典或者数组对象传递给<foreach>作为集合参数。当使用可迭代对象或者数组时,index是当前迭代的次数,item的值是本次迭代获取的元素。当使用字典(或者Map.Entry对象的集合)时,index是键,item是值。

在使用<foreach>时最关键也是最容易出错的就是collection属性,该属性是必须指定的,而且在不同情况下,该属性的值是不一样的。主要有以下3种情况:

  1. 如果传入的是单参数且参数类型是一个数组或者List的时候,collection属性值分别为array和list(或collection);

  2. 如果传入的参数是多个的时候,就需要把它们封装成一个Map了,当然单参数也可以封装成Map集合,这时候collection属性值就为Map的键。

  3. 如果传入的参数是POJO包装类的时候,collection属性值就为该包装类中需要进行遍历的数组或集合的属性名。

所以在设置collection属性值的时候,必须按照实际情况配置,否则程序就会出现异常。

4. <choose>、<when>、<otherwise>元素只选择一个条件执行

 当多个条件都成立时,只根据第一个成立的条件查询;当一个条件成立时就根据这一个查询;当没有条件成立时根据otherwise查询

      <select id="searchStudent" resultMap="studentMap">
        select sid,sname,sgender,sage,scid
        from students
      
        where 1=1
        <choose>
            <when test="gender!=null and gender!='' ">
                and sgender=#{gender}
            </when>
            <when test="age!=null and age!=0">
                and sage=#{age}
            </when>
            <otherwise>
                and scid=2
            </otherwise>
        </choose>

    </select>

5.<set>元素

<set>元素主要用于更新操作,更新的某一个或几个字段,其主要作用是在动态包含的SQL语句前输出一个SET关键字,并将SQL语句中最后一个多余的逗号去除。

    //更新学生信息,只更新某个字段而非全部重写
    public int updateStudent(Student student);
@Test
    public void updateStudent() {
        StudentDAO studentDAO=mybatisUtils.getMapper(StudentDAO.class);
        Student student= new Student();
        student.setStuId(8021);
        student.setStuAge(21);
        student.setStuName("小华");
        int i=studentDAO.updateStudent(student);
        System.out.println(i);
    }
    <update id="updateStudent" parameterType="pojo.Student">
        update students
        <set>
            <if test="stuName!=null and stuName!='' " >
                sname=#{stuName},
            </if>
            <if test="stuGender!=null and stuGender!='' " >
                sgender=#{stuGender},
            </if>
            <if test="stuAge!=null and stuAge!=0 " >
                sage=#{stuAge},
            </if>
        </set>
        where sid=#{stuId}
    </update>

如果<set>元素内包含的内容都为空,则会出现SQL语法错误。所以在使用<set>元素进行字段信息更新时,要确保传入的更新字段不能都为空。

6.<bind>元素

在进行模糊查询编写SQL语句的时候,如果使用“${}”进行字符串拼接,则无法防止SQL注入问题;如果使用concat函数进行拼接,则只针对MySQL数据库有效;如果使用的是Oracle数据库,则要使用连接符号“||”。这样,映射文件中的SQL就要根据不同的情况提供不同形式的实现,这显然是比较麻烦的,且不利于项目的移植。为此,MyBatis提供了<bind>元素来解决这一问题,我们完全不必使用数据库语言,只要使用MyBatis的语言即可与所需参数连接。

MyBatis的<bind>元素可以通过OGNL表达式来创建一个上下文变量,其使用方式如下:

<!--<bind>元素的使用:根据客户名模糊查询客户信息 -->
<select id="findCustomerByName" parameterType="com.itheima.po.Customer"
          resultType="com.itheima.po.Customer">
    <!--_parameter.getUsername()也可直接写成传入的字段属性名,即username-->            <bind name="pattern_username" 
                                value="'%'+_parameter.getUsername()+'%'" />
    select * from t_customer 
where 
    username like #{pattern_username}
</select>

上述配置代码中,使用<bind>元素定义了一个name为pattern_username的变量,<bind>元素中value的属性值就是拼接的查询字符串,其中_parameter.getUsername()表示传递进来的参数(也可以直接写成对应的参数变量名,如username)。在SQL语句中,直接引用<bind>元素的name属性值即可进行动态SQL组装。

测试:

    //模糊查询,防止sql注入
    public List<Student> searchStudentByName(String name);
    @Test
    public void searchStudentByName() {
        StudentDAO studentDAO=mybatisUtils.getMapper(StudentDAO.class);
        List<Student> studentList=studentDAO.searchStudentByName("刚");
        studentList.forEach(System.out::println);
    }
    <select id="searchStudentByName" parameterType="String" resultMap="studentMap">
        <bind name="nameparams" value=" '%'+ name +'%' "/>
        select sid,sname,sgender,sage,scid
        from students
        where sname like #{nameparams}
    </select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值