set标签

存放修改方法,我们之前写的更新方法是全字段的更新,或者是指定字段的更新,现在我想实现一个新功能,传入的Employee包含什么字段,数据库就更新相对应的列值:

如果我们啥也不做直接上<if>标签看看会发生什么

  1. <update id="updateEmp">  
  2.     update tb_employee set  
  3.     <if test="lastName!=null">  
  4.         last_name = #{lastName},  
  5.     </if>  
  6.     <if test="email!=null">  
  7.         email=#{email},  
  8.     </if>  
  9.     <if test="gender!=null">  
  10.         gender=#{gender}  
  11.     </if>  
  12.     where id=#{id}  
  13. </update> 
  1. @Test  
  2. public void testGetEmpsByConditionIf() throws IOException {  
  3.     SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  
  4.     SqlSession openSession = sqlSessionFactory.openSession(true);  
  5.     try {  
  6.         EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);  
  7.         Employee e = new Employee();  
  8.         e.setId(5);  
  9.         e.setLastName("王大锤");  
  10.         mapper.updateEmp(e);  
  11.     }finally {  
  12.             
  13.         openSession.close();  
  14.     }  
  15. }  

DEBUG [main] - ==> Preparing: update tb_employee set last_name = ?, where id=?

出错原因很明显,多出了个逗号,接下来将这些<if>标签套在<set>再做尝试

  1. <update id="updateEmp">  
  2.     update tb_employee  
  3.     <set>  
  4.         <if test="lastName!=null">  
  5.             last_name = #{lastName},  
  6.         </if>  
  7.         <if test="email!=null">  
  8.             email=#{email},  
  9.         </if>  
  10.         <if test="gender!=null">  
  11.             gender=#{gender}  
  12.         </if>  
  13.     </set>  
  14.     where id=#{id}  
  15. </update>  

发现成功,同样的我们也可以用<trim>标签实现

  1. <update id="updateEmp">  
  2.     update tb_employee  
  3.     <trim prefix="set" suffixOverrides=",">  
  4.         <if test="lastName!=null">  
  5.             last_name = #{lastName},  
  6.         </if>  
  7.         <if test="email!=null">  
  8.             email=#{email},  
  9.         </if>  
  10.         <if test="gender!=null">  
  11.             gender=#{gender}  
  12.         </if>  
  13.     </trim>  
  14.     where id=#{id}  
  15. </update>  

foreach标签

<foreach>可以应用于SQL语句中where id in(…….)这种类型的查询。

<foreach>含有两个属性,一个是collection,指定要遍历的集合,另外一个是item,即将当前遍历的元素赋给指定的变量,接下来我们使用#{变量名}就可以取出变量的值,也就是当前遍历出的元素,

  1. <select id="getEmpsByConditionForeach" resultType="com.figsprite.bean.Employee">  
  2.     select * from tb_employee where id in (  
  3.     <foreach collection="ids" item="item_id" separator="," >  
  4.         #{item_id}  
  5.     </foreach>  
  6.     )  
  7. </select>

属性separate指定元素之间的分隔符,当然上面的写法有些不美观()中套着很多东西,不方便查看,因此,我们再使用两个其他属性,让编码更加美观:

  1. <select id="getEmpsByConditionForeach" resultType="com.figsprite.bean.Employee">  
  2.     select * from tb_employee    
  3.     <foreach collection="ids" item="item_id" separator="," open=" where id in (" close=")">  
  4.         #{item_id}  
  5.     </foreach>  
  6. </select>  

注意括号不要写成中文的,不然这里的括号很难看出中英文差别。

还有一个属性index ,当遍历list时,它代表索引,当遍历map是,它就成了key

List<Employee> getEmpsByConditionForeach(@Param("ids") List<Integer> ids);

  1. @Test  
  2. public void testGetEmpsByCondition() throws IOException {  
  3.     SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  
  4.     SqlSession openSession = sqlSessionFactory.openSession(true);  
  5.     try {  
  6.         EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);  
  7.     
  8.         List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(6,7));  
  9.         for (Employee emp : list) {  
  10.             System.out.println(emp);  
  11.         }  
  12.     }finally {  
  13.     
  14.         openSession.close();  
  15.     }  
  16. }  

DEBUG [main] - ==> Preparing: select * from tb_employee where id in ( ? , ? )

DEBUG [main] - ==> Parameters: 6(Integer), 7(Integer)

DEBUG [main] - <== Total: 2

Employee{id=6, lastName='吴花琴', gender='0', email='qweqwe', department=null}

Employee{id=7, lastName='吴小明', gender='1', email='wewqewq', department=null}

<foreach>标签 批量保存

在MYSQL中,我们如果想批量插入就要用到以下方式的SQL语句:

  1. INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES('tom','sdasdasd@gmail.com','0',1),  
  2. ('jerry','asdasd@qq.com','0',1);  

同样我们可以通过<foreach>来实现这个功能

void addEmps(@Param("emps") List<Employee> emps);
  1. <insert id="addEmps">  
  2.     INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES  
  3.     <foreach collection="emps" item="emp" separator=",">  
  4.         (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})  
  5.     </foreach>  
  6. </insert> 
  1. @Test  
  2. public void TestSaveBach() throws IOException {  
  3.     SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  
  4.     SqlSession openSession = sqlSessionFactory.openSession(true);  
  5.     Department department = new Department(2);  
  6.     Employee e1 = new Employee("Wendy","0","adcxs@qq.com",department);  
  7.     Employee e2 = new Employee("Diyago","1","aaasaadccjdjj@qq.con",department);  
  8.     List<Employee> employeeList = new ArrayList<>();  
  9.     employeeList.add(e1);  
  10.     employeeList.add(e2);  
  11.     try{  
  12.         EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);  
  13.         mapper.addEmps(employeeList);  
  14.     }finally {  
  15.         openSession.close();  
  16.     }  
  17. }

DEBUG [main] - ==> Preparing: INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES (?,?,?,?) , (?,?,?,?)

MySQl支持这种VALUES ( ),( ),( ),还可以这么写:

每次取出一个员工,就插入

  1. <insert id="addEmps">  
  2.     
  3.     <foreach collection="emps" item="emp" separator=";">  
  4.         INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES  
  5.         (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})  
  6.     </foreach>  
  7. </insert>  

发现出错了,主要原因JDBC链接属性不能支持多SQL语句用;分开的形式,我们需要将这个选项开启,其中有一个allowMultiQueries,我们只要把它的值改成true即可,

jdbc.url=jdbc:mysql://localhost:3306/mybatis_learn?allowMultiQueries=true

,再去尝试,发现就可以了,这种方式也可以用于批量修改和删除,十分方便

动态SQL2的更多相关文章

  1. 存储过程中执行动态Sql语句

    MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_executesql;通常,sp_executesql则更具有优势,它提供了输入输出接口,而EXEC没有.还有一个最大的好处就 ...

  2. 获取动态SQL的返回结果

    1. 介绍说明 有时候在执行存储过程后,需要获取存储过程返回的列表,然后进行相应操作的情况,或者执行动态语句,获取返回结果的情况,通过EXEC ,sp_executesql可以实现该功能. 网上也有很 ...

  3. Java动态菜单添加

    自己做出来的添加数据库配置好的动态菜单的方法 private void createMenu() {  IMenuDAO dao = new MenuDAOImpl();  String sql1 = ...

  4. 怎样SQL存储过程中执行动态SQL语句

    MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_executesql;通常,sp_executesql则更具有优势,它提供了输入输出接口,而EXEC没有.还有一个最大的好处就 ...

  5. mysql 存储过程动态执行sql语句

    之前经常在程序中拼接sql语句,其实我们也可以在存储过程中拼接sql 语句,动态的执行~~ 代码如下: DROP PROCEDURE IF EXISTS SearchByDoctor;CREATE P ...

  6. 在论坛中出现的比较难的sql问题:39(动态行转列 动态日期列问题)

    原文:在论坛中出现的比较难的sql问题:39(动态行转列 动态日期列问题) 最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了. 所以,觉 ...

  7. MOOC课程信息D3.js动态可视化

    版权声明:本文为博主原创文章,转载 请注明出处:https://blog.csdn.net/sc2079/article/details/83153693 - 写在前面 好久没更新博客了,主要还是最近 ...

  8. java动态代理框架

             java动态代理是一个挺有意思的东西,他有时候可以被使用的很灵活.像rpc的调用,调用方只是定义的一个接口,动态代理让他匹配上对应的不同接口:mybatis内部的实现,编码时,只是实 ...

  9. SqlServer:SqlServer(存储过程动态表查询(取消返回值),事务处理,批量还原sqlserver备份,强制删除被占用的数据库)

    1.存储过程动态表查询 USE [NETWORKING_AUDIT] GO /****** Object: StoredProcedure [dbo].[impConfigInfo] Script D ...

随机推荐

  1. CSAPP:信息的表和处理2

    CSAPP:信息的表和处理2 关键点:浮点数.浮点数运算. 二进制小数IEEE浮点数表示浮点数转换(单精度)参考 二进制小数   形如表示的二进制数,其中每个位的取值范围位0和1.这种表示方式的定义如 ...

  2. [国家集训队]happiness

    嘟嘟嘟 就这么建. --- #include<cstdio> #include<iostream> #include<cmath> #include<algo ...

  3. 转://Oracle中User和Schema的区别和联系

    今天在阅读Oracle官方文档的时候,读到schema的基本概念,这就让我产生了一个疑问:user和schema两者之间到底有什么区别?为了更深层次的理解二者之间的区别和联系,以下是官方文档中关于us ...

  4. 静默安装Oracle12.2数据库

    实验环境: 操作系统:Redhat 6.4 64位 数  据 库:Oracle 12c R2   一. 安装前准备 1. 创建用户和组 [root@wjq ~]# groupadd -g 1000 o ...

  5. 转://Oracle 复合压缩索引场景及性能对比

    摘要:今天为什么提到这个话题,出于一个偶然,一个同事在优化新开发的系统时向我请教如何添加复合压缩索引的问题.我总结了一下,问题有三. 第一:需不需要压缩 第二:对第几列压缩 第三:性能对比,选出最优 ...

  6. automake - 使用 autotools 工具集

    一般而言,对于小项目或玩具程序,手动编写 Makefile 即可.但对于大型项目,手动编写维护 Makefile 成为一件费时费力的无聊工作. 本文介绍 autotools 工具集自动生成符合 Lin ...

  7. Spring Security(四):2.1 Introduction What is Spring Security?

    Spring Security provides comprehensive security services for Java EE-based enterprise software appli ...

  8. 1-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案数据篇(视频总揽和功能演示)

    主要实现的功能 其它视频和资料稍候再补充上 我先写后面的文章 2-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案数据篇(安装数据库,数据库简单说明)

  9. 深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 3

    备注: 因为文章太长,所以将它分为三部分,本文是第三部分. 第一部分:深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 1 第二部分:深入浅出经典面试题:从浏览器中输入URL ...

  10. .net core实践系列之SSO-跨域实现

    前言 接着上篇的<.net core实践系列之SSO-同域实现>,这次来聊聊SSO跨域的实现方式.这次虽说是.net core实践,但是核心点使用jquery居多. 建议看这篇文章的朋友可 ...