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. Python3新特性 类型注解 以及 点点点

    Python3新特性 类型注解 以及 点点点 ... Python3 的新特性 Python 是一种动态语言,变量以及函数的参数是 不区分类型 的 在 函数中使用类型注解 相当于 给 形参的 类型 设 ...

  2. WPF自定义控件(二)の重写原生控件样式模板

    话外篇: 要写一个圆形控件,用Clip,重写模板,去除样式引用圆形图片可以有这三种方式. 开发过程中,我们有时候用WPF原生的控件就能实现自己的需求,但是样式.风格并不能满足我们的需求,那么我们该怎么 ...

  3. python六十四课——高阶函数练习题(一)

    1.lt = ['sdfasdfa', 'ewqrewrewqr', 'dsafa12312fdsafd', 'safsadf'] --> 得到长度列表2.tp = ('TOM', 'Lilei ...

  4. eclipse导入maven项目, A resource exists with a different case: '/xxx'.

    eclipse 导入maven 项目出现 这是由于你的workspace里有相同的项目, 这时在metadata里可以看到所有的project信息 只需在eclipse的package explore ...

  5. 安全管理器SecurityManager

    一.文章的目的 这是一篇对Java安全管理器入门的文章,目的是简单了解什么是SecurityManager,对管理器进行简单配置,解决简单问题. 比如在阅读源码的时候,发现这样的代码,想了解是做什么的 ...

  6. [python] os.path.join() 与 sys.path

    脚本文件本地目录挂入系统环境变量 import sys, os sys.path.append(os.pardir) print(sys.path) os.getcwd()获取当前目录路径 impor ...

  7. flash设置里面:您的 Flash 设置会一直保留到您退出 Chrome 为止。

    疑问:flash设置里面:您的 Flash 设置会一直保留到您退出 Chrome 为止. 我记得以前的版本配置后就一直用啊,允许的就可以一直允许,现在这个sb版本退出后就恢复到默认,允许列表的网站就清 ...

  8. Zookeeper系列一:Zookeeper介绍、Zookeeper安装配置、ZK Shell的使用

    https://www.cnblogs.com/leeSmall/p/9563547.html 一.Zookeeper介绍 1. 介绍Zookeeper之前先来介绍一下分布式 1.1 分布式主要是下面 ...

  9. node.js之Cookie

    最近还是用node.js比较多,今天正好遇见一个问题,还是关于Cookie. node.js中如何实现cookie(以express框架为例): "use strict"; var ...

  10. Python实现机器人聊天

    今天午休的时候,无意之中看了一篇博客,名字叫Python实现机器人,感觉挺有的意思的.于是用其写了一个简单的Python聊天,源码如下所示: # -*- coding: utf- -*- import ...