首页 > 技术文章 > MyBatis3_[tp_41-42-43]-_动态sql_trim_自定义字符串截取_choose分支选择_update的set与if-trim 结合的动态更新

zhazhaacmer 2018-12-04 17:29 原文

 

笔记要点
出错分析与总结

/** 笔记:
 *  查询的时候,如果某些条件,没带可能SQL拼装会有问题;
 *      1.-->给where 后面加上 1=1, 以后的条件都and XXX
 *      2. <where> </where> 标签加上后,就不用写SQL的 where 条件语句!
 *      3. trim 字符串截取 (~where(封装查询条件),set(封装修改条件) )
 *      4. foreach()
 */


工程组织

数据库组织

0.重新修改Bean类

1.定义接口

package com.dao;

import com.bean.Employee;

import java.util.List;

public interface EmployeeMapper_DynamicSQL {

    public List<Employee> getEmpsByConditionIf(Employee e);

    public List<Employee> getEmpsByConditionTrim(Employee e);

    public List<Employee> getEmpsByConditionChoose(Employee e);

    public void updateEmp(Employee e);  //执行更新操作,能更新多少更新多少,弹性最大限度地进行更新!

    public void updateEmpByTrim(Employee e);  //修改


}
View Code

 

2.定义XML映射文件

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <!--动态SQL几个主要模块:-->
        <!--if 标签
             test="判断表达式,OGNL语法(参照PPT)"
              :从传入的参数中取值判断,
              遇见特殊符号,写转义字符!-> and : &amp;&amp;  "" : &quot;&quot;
                    或者写单引号也可以!!
                    网址: W3CSchool->html教程->ISO-8859-> ASCII编码
             OGNL : 会进行字符串与数字的转换判断 "0"==0 ,"1"==1 ;
        -->
        <!--where 标签
             查询的时候,如果某些条件,没带可能SQL拼装会有问题;
             给where 后面加上 1=1, 以后的条件都and XXX
             2.mybatis 使用where 标签来将所有的查询条件包含在内,
                    自动去掉拼接后的SQL 的前面的多出来的and 或者or ;在后面的就不可以了!
        -->
        <!--Trim标签
            如果 where 元素没有按正常套路出牌,我们可以通过自定义 trim 元素来定制 where 元素的功能;
            prefixOverrides 属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的)。
                它的作用是移除所有指定在 prefixOverrides 属性中的内容,并且插入 prefix 属性中指定的内容。
        -->

        <!--choose (when, otherwise)  : 分支选择 ,类似于Java的switch-case
            eg:带了id用id查,没有就用lastName来查; 只会选择一个!
        -->
        <!--trim (where, set)-->
        <!--foreach-->
<mapper namespace="com.dao.EmployeeMapper_DynamicSQL">
    <!--1.查询员工,要求,携带了那个字段查询条件就带上那个条件的值;
            传入两个条件进行模糊查询-->
    <select id="getEmpsByConditionIf" resultType="com.bean.Employee">
        select * from tbl_employee

        <where>
            <if test="lastName !=null and lastName !='jerry' ">
               and last_name like #{lastName}
            </if>
            <if test="id != null">
                and  id=#{id}
            </if>
      </where>

  </select>

    <select id="getEmpsByConditionTrim" resultType="com.bean.Employee">
        select * from tbl_employee

        <trim prefix="where" prefixOverrides="and | or">
            <if test="lastName !=null and lastName !='jerry' ">
                and last_name like #{lastName} and
            </if>
            <if test="id != null">
                and  id=#{id}
            </if>
        </trim>
    </select>

    <select id="getEmpsByConditionChoose" resultType="com.bean.Employee">
        select * from tbl_employee
        <where>
            <choose>
                <when test="id != null">
                     id=#{id}
                </when>
                <when test="lastName !=null and lastName !='jerry' ">
                    and last_name like #{lastName}
                </when>
                <otherwise>
                      1=1
                </otherwise>
            </choose>

        </where>

    </select>

    <!--public void updateEmp(Employee e);-->
    <update id="updateEmp">
        update tbl_employee
         <set>
             <if test="lastName!=null">last_name=#{lastName},</if>
             <if test="email!=null">email=#{email},</if>
             <if test="gender!=null">gender=#{gender}</if>
         </set>
        where id=#{id}
    </update>

    <update id="updateEmpByTrim">
        update tbl_employee
        <trim prefix="set" suffixOverrides=",">
            <if test="lastName!=null">last_name=#{lastName},</if>
            <if test="email!=null">email=#{email},</if>
            <if test="gender!=null">gender=#{gender},</if>
        </trim>
         where id=#{id}
    </update>
</mapper>

 

3.编写测试代码

   public SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(inputStream);
        }
    @Test
    public void test09() throws Exception {
        SqlSession openSession = getSqlSessionFactory().openSession();
        try {
            System.out.println("++++++++++---- 3.测试 动态SQL元素:choose关键字!");
            EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class);
            Employee employee = new Employee(null, "%e%", null, null);
            List<Employee> emps = mapper.getEmpsByConditionChoose(employee);
            for (Employee e:emps)
                System.out.println(e);
            openSession.commit();
        } finally {
            openSession.close();
        }
    }
    @Test
    public void test10() throws Exception {
        SqlSession openSession = getSqlSessionFactory().openSession();
        try {
//            System.out.println("++++++++++---- 4.测试 动态SQL元素:update与set关键字!");
//            EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class);
//            Employee employee = new Employee(1, "Jerry", "...@...", "1");
//            mapper.updateEmp(employee);
            System.out.println("++++++++++---- 5.测试 动态SQL元素:trim与set关键字!");
            EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class);
            Employee employee = new Employee(1, "Jerry2333", "233@...", null);
            mapper.updateEmpByTrim(employee);
            openSession.commit();
        } finally {
            openSession.close();
        }
    }

 

推荐阅读