Springboot Mybatis 动态SQL

打印 上一主题 下一主题

主题 973|帖子 973|积分 2919

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
        动态SQL
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4.         "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.wzb.SqlImprove20240925.SQLImproveMapper">
  6.     <!-- 将条件查询改成动态SQL形式 -->
  7.     <!-- XML中,是对SQL语句进行拼接的,将若干SQL语句的条件,拼接成一条完整的SQL语句 -->
  8.     <!-- <if>标签用于判断条件是否成立,用test属性进行条件判断,若条件为true,那么就拼接SQL,若为false,则不操作 -->
  9.     <!--    <select id="sqlImprove" resultType="com.wzb.Pojo20240925.Emp">-->
  10.     <!--        select * from emp-->
  11.     <!--        where-->
  12.     <!--        <if test="name != null">-->
  13.     <!--            name like concat('%', #{name}, '%')-->
  14.     <!--        </if>-->
  15.     <!--        <if test="gender != -1">-->
  16.     <!--            and gender = #{gender}-->
  17.     <!--        </if>-->
  18.     <!--        <if test="begin != null and end != null">-->
  19.     <!--            and entrydate between #{begin} and #{end}-->
  20.     <!--        </if>-->
  21.     <!--        order by update_time desc-->
  22.     <!--    </select>-->
  23.     <!-- 上述代码看似完成了条件查询,但其实仍然有不足之处:
  24.     1.若所有参数都是null,那么仍然会在SQL语句中拼接where,这是不符合SQL语法的
  25.     2.若前面的是null,但是后面的参数不是null,那么会多拼接一个null,比如上面的代码:name是null;但是gender不是null
  26.       那么就会拼接成“...... where and gender = #{gender}”,这是错误的SQL语句
  27.     -->
  28.     <!-- 解决方法:<where>标签:
  29.          <where>标签只会在子元素(参数)有内容的情况下,才会插入where子句,并且能够自动去除子句开头的and或者or -->
  30.     <!-- 优化代码 -->
  31.     <!-- 当参数没有传递(为null时),就不会将语句拼接成SQL语句,并且用了<where>标签,能够自动处理开头的and、or -->
  32.     <select id="sqlImprove" resultType="com.wzb.Pojo20240925.Emp">
  33.         select * from emp
  34.         <where>
  35.             <if test="name != null">
  36.                 and name like concat('%', #{name}, '%')
  37.             </if>
  38.             <if test="gender != -1">
  39.                 and gender = #{gender}
  40.             </if>
  41.             <if test="begin != null and end != null">
  42.                 and entrydate between begin and end
  43.             </if>
  44.         </where>
  45.         order by update_time desc
  46.     </select>
  47.     <!-- 测试成功,成功实现动态SQL -->
  48.     <!-- 实现动态更新员工信息 -->
  49. <!--    <update id="updateImprove">-->
  50. <!--        update emp-->
  51. <!--        set-->
  52. <!--        <if test="username != null">-->
  53. <!--            username=#{username},-->
  54. <!--        </if>-->
  55. <!--        <if test="name != null">-->
  56. <!--            name=#{name},-->
  57. <!--        </if>-->
  58. <!--        <if test="gender != -1">-->
  59. <!--            gender=#{gender},-->
  60. <!--        </if>-->
  61. <!--        <if test="image != null">-->
  62. <!--            image=#{image},-->
  63. <!--        </if>-->
  64. <!--        <if test="job != null">-->
  65. <!--            job=#{job},-->
  66. <!--        </if>-->
  67. <!--        <if test="entrydate != null">-->
  68. <!--            entrydate=#{entrydate},-->
  69. <!--        </if>-->
  70. <!--        <if test="deptId != null">-->
  71. <!--            dept_id=#{deptId},-->
  72. <!--        </if>-->
  73. <!--        <if test="updateTime != null">-->
  74. <!--            update_time=#{updateTime}-->
  75. <!--        </if>-->
  76. <!--        where id = #{id}-->
  77. <!--    </update>-->
  78.     <!-- 这个代码会出现问题,若只传递前面的参数,不传递最后一个参数,那么将会多出一个“,”(因为每一个拼接语句的末尾都有个逗号,
  79.     只有最后一1个拼接语句没有),所以说只要不传递最后一个参数,就会发生SQL语句语法错误 -->
  80.     <!-- 解决方法:使用标签<set>
  81.          在update语句中使用<set>标签,会删除掉额外的逗号,避免SQL语法错误 -->
  82.     <update id="updateImprove">
  83.         update emp
  84.         <set>
  85.             <if test="username != null">
  86.                 username=#{username},
  87.             </if>
  88.             <if test="name != null">
  89.                 name=#{name},
  90.             </if>
  91.             <if test="gender != -1">
  92.                 gender=#{gender},
  93.             </if>
  94.             <if test="image != null">
  95.                 image=#{image},
  96.             </if>
  97.             <if test="job != null">
  98.                 job=#{job},
  99.             </if>
  100.             <if test="entrydate != null">
  101.                 entrydate=#{entrydate},
  102.             </if>
  103.             <if test="deptId != null">
  104.                 dept_id=#{deptId},
  105.             </if>
  106.             <if test="updateTime != null">
  107.                 update_time=#{updateTime}
  108.             </if>
  109.         </set>
  110.         where id = #{id}
  111.     </update>
  112.     <!-- 这样可以解决update语句后多","的问题 -->
  113.     <!-- 小结:
  114.          <if>标签可以用于判断条件是否成立,若条件为true,那么拼接对应的SQL语句
  115.          <where>标签代替where,只会在子元素不为null的时候才插入where子句,并且能够自动去除子句开头的多余的and和or
  116.          <set>标签代替set在update语句中使用,可以动态的插入update子句,并且能删除额外的“,” -->
  117.     <!-- 使用<foreach>标签达到删除多条语句的效果 -->
  118.     <!-- <foreach collection="集合名称" item="集合遍历出来的元素", separator="每一次遍历使用的分隔符"
  119.           open="遍历开始之前拼接的片段" close="遍历结束后拼接的片段"> -->
  120.     <delete id="deleteImprove">
  121.         delete from emp where id in
  122.         <foreach collection="ids" item="id" separator="," open="(" close=")">
  123.             #{id}
  124.         </foreach>
  125.     </delete>
  126.     <!-- 成功使用<foreach>完成批量删除 -->
  127.     <!-- 在XML映射文件中配置SQL,有时会出现很多重复的片段,那么就会导致很多冗余的代码 -->
  128. </mapper>
复制代码
        SQLImproveMapper
  1. package com.wzb;
  2. import com.wzb.MybatisExercise20240925.EmpMapper;
  3. import com.wzb.MybatisXmlExercise20240925.XmlMapper;
  4. import com.wzb.Pojo20240925.Emp;
  5. import com.wzb.SqlImprove20240925.SQLImproveMapper;
  6. import org.junit.jupiter.api.Test;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import java.time.LocalDate;
  10. import java.time.LocalDateTime;
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.List;
  14. @SpringBootTest
  15. class SpringbootExercise20240925ApplicationTests {
  16.     @Autowired
  17.     private EmpMapper empMapper;
  18.     @Autowired
  19.     private XmlMapper xmlMapper;
  20.     @Autowired
  21.     private SQLImproveMapper sqlImproveMapper;
  22.     // 增
  23. //    @Test
  24. //    public void insertEmp() {
  25. //        Emp emp = new Emp();
  26. //        emp.setUsername("black");
  27. //        emp.setName("布莱克");
  28. //        emp.setGender((short)1);
  29. //        emp.setImage("2.jpg");
  30. //        emp.setJob((short)2);
  31. //        emp.setEntrydate(LocalDate.of(2000, 1, 1));
  32. //        emp.setCreateTime(LocalDateTime.now());
  33. //        emp.setUpdateTime(LocalDateTime.now());
  34. //
  35. //        empMapper.insertEmp(emp);
  36. //    }
  37. //    // 删
  38. //    @Test
  39. //    public void deleteEmp() {
  40. //        empMapper.deleteEmp(20);
  41. //    }
  42. //
  43. //    // 改
  44. //    @Test
  45. //    public void updateEmp() {
  46. //        Emp emp = new Emp();
  47. //        emp.setId(19);
  48. //        emp.setUsername("gaiya");
  49. //        emp.setName("盖亚");
  50. //        emp.setGender((short)1);
  51. //        emp.setImage("2.jpg");
  52. //        emp.setJob((short)2);
  53. //        emp.setEntrydate(LocalDate.of(2000, 1, 1));
  54. //        emp.setCreateTime(LocalDateTime.now());
  55. //        emp.setUpdateTime(LocalDateTime.now());
  56. //
  57. //        empMapper.updateEmp(emp);
  58. //    }
  59. //
  60. //    // 查
  61. //    @Test
  62. //    public void selectEmp() {
  63. //        Emp emp = empMapper.selectEmp(19);
  64. //        System.out.println(emp);
  65. //    }
  66.     @Test
  67.     public void XmlConditionSelect() {
  68.         List<Emp> empList = xmlMapper.conditionSelect("张", (short) 1, null, null
  69.                 /*LocalDate.of(2000, 1, 1), LocalDate.of(2024,1,1)*/);
  70.         for (Emp emp : empList) {
  71.             System.out.println(emp);
  72.         }
  73.     }
  74.     @Test
  75.     public void SqlImprove() {
  76.         List<Emp> empList = sqlImproveMapper.sqlImprove(null, (short) -1, null, null);
  77.         for (Emp emp : empList) {
  78.             System.out.println(emp);
  79.         }
  80.     }
  81.     @Test
  82.     public void updateEmp() {
  83.         Emp emp = new Emp();
  84.         emp.setUsername("tom2");
  85.         sqlImproveMapper.updateImprove(emp);
  86.     }
  87.     @Test
  88.     public void deleteEmp() {
  89.         List<Integer> ids = new ArrayList<>();
  90.         Collections.addAll(ids, 18,19,26,27);
  91.         sqlImproveMapper.deleteImprove(ids);
  92.     }
  93. }
复制代码
 


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

雁过留声

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表