动态SQL2
set标签
存放修改方法,我们之前写的更新方法是全字段的更新,或者是指定字段的更新,现在我想实现一个新功能,传入的Employee包含什么字段,数据库就更新相对应的列值:
如果我们啥也不做直接上<if>标签看看会发生什么
- <update id="updateEmp">
- update tb_employee set
- <if test="lastName!=null">
- last_name = #{lastName},
- </if>
- <if test="email!=null">
- email=#{email},
- </if>
- <if test="gender!=null">
- gender=#{gender}
- </if>
- where id=#{id}
- </update>
- @Test
- public void testGetEmpsByConditionIf() throws IOException {
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- SqlSession openSession = sqlSessionFactory.openSession(true);
- try {
- EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);
- Employee e = new Employee();
- e.setId(5);
- e.setLastName("王大锤");
- mapper.updateEmp(e);
- }finally {
- openSession.close();
- }
- }
DEBUG [main] - ==> Preparing: update tb_employee set last_name = ?, where id=?
出错原因很明显,多出了个逗号,接下来将这些<if>标签套在<set>再做尝试
- <update id="updateEmp">
- update tb_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>
发现成功,同样的我们也可以用<trim>标签实现
- <update id="updateEmp">
- update tb_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>
foreach标签
<foreach>可以应用于SQL语句中where id in(…….)这种类型的查询。
<foreach>含有两个属性,一个是collection,指定要遍历的集合,另外一个是item,即将当前遍历的元素赋给指定的变量,接下来我们使用#{变量名}就可以取出变量的值,也就是当前遍历出的元素,
- <select id="getEmpsByConditionForeach" resultType="com.figsprite.bean.Employee">
- select * from tb_employee where id in (
- <foreach collection="ids" item="item_id" separator="," >
- #{item_id}
- </foreach>
- )
- </select>
属性separate指定元素之间的分隔符,当然上面的写法有些不美观()中套着很多东西,不方便查看,因此,我们再使用两个其他属性,让编码更加美观:
- <select id="getEmpsByConditionForeach" resultType="com.figsprite.bean.Employee">
- select * from tb_employee
- <foreach collection="ids" item="item_id" separator="," open=" where id in (" close=")">
- #{item_id}
- </foreach>
- </select>
注意括号不要写成中文的,不然这里的括号很难看出中英文差别。
还有一个属性index ,当遍历list时,它代表索引,当遍历map是,它就成了key
List<Employee> getEmpsByConditionForeach(@Param("ids") List<Integer> ids);
- @Test
- public void testGetEmpsByCondition() throws IOException {
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- SqlSession openSession = sqlSessionFactory.openSession(true);
- try {
- EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);
- List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(6,7));
- for (Employee emp : list) {
- System.out.println(emp);
- }
- }finally {
- openSession.close();
- }
- }
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语句:
- INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES('tom','sdasdasd@gmail.com','0',1),
- ('jerry','asdasd@qq.com','0',1);
同样我们可以通过<foreach>来实现这个功能
void addEmps(@Param("emps") List<Employee> emps);
- <insert id="addEmps">
- INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES
- <foreach collection="emps" item="emp" separator=",">
- (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})
- </foreach>
- </insert>
- @Test
- public void TestSaveBach() throws IOException {
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- SqlSession openSession = sqlSessionFactory.openSession(true);
- Department department = new Department(2);
- Employee e1 = new Employee("Wendy","0","adcxs@qq.com",department);
- Employee e2 = new Employee("Diyago","1","aaasaadccjdjj@qq.con",department);
- List<Employee> employeeList = new ArrayList<>();
- employeeList.add(e1);
- employeeList.add(e2);
- try{
- EmployeeMapperDynamic mapper = openSession.getMapper(EmployeeMapperDynamic.class);
- mapper.addEmps(employeeList);
- }finally {
- openSession.close();
- }
- }
DEBUG [main] - ==> Preparing: INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES (?,?,?,?) , (?,?,?,?)
MySQl支持这种VALUES ( ),( ),( ),还可以这么写:
每次取出一个员工,就插入
- <insert id="addEmps">
- <foreach collection="emps" item="emp" separator=";">
- INSERT INTO tb_employee(last_name,email,gender,d_id) VALUES
- (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})
- </foreach>
- </insert>
发现出错了,主要原因JDBC链接属性不能支持多SQL语句用;分开的形式,我们需要将这个选项开启,其中有一个allowMultiQueries,我们只要把它的值改成true即可,
jdbc.url=jdbc:mysql://localhost:3306/mybatis_learn?allowMultiQueries=true
,再去尝试,发现就可以了,这种方式也可以用于批量修改和删除,十分方便
动态SQL2的更多相关文章
- 存储过程中执行动态Sql语句
MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_executesql;通常,sp_executesql则更具有优势,它提供了输入输出接口,而EXEC没有.还有一个最大的好处就 ...
- 获取动态SQL的返回结果
1. 介绍说明 有时候在执行存储过程后,需要获取存储过程返回的列表,然后进行相应操作的情况,或者执行动态语句,获取返回结果的情况,通过EXEC ,sp_executesql可以实现该功能. 网上也有很 ...
- Java动态菜单添加
自己做出来的添加数据库配置好的动态菜单的方法 private void createMenu() { IMenuDAO dao = new MenuDAOImpl(); String sql1 = ...
- 怎样SQL存储过程中执行动态SQL语句
MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_executesql;通常,sp_executesql则更具有优势,它提供了输入输出接口,而EXEC没有.还有一个最大的好处就 ...
- mysql 存储过程动态执行sql语句
之前经常在程序中拼接sql语句,其实我们也可以在存储过程中拼接sql 语句,动态的执行~~ 代码如下: DROP PROCEDURE IF EXISTS SearchByDoctor;CREATE P ...
- 在论坛中出现的比较难的sql问题:39(动态行转列 动态日期列问题)
原文:在论坛中出现的比较难的sql问题:39(动态行转列 动态日期列问题) 最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了. 所以,觉 ...
- MOOC课程信息D3.js动态可视化
版权声明:本文为博主原创文章,转载 请注明出处:https://blog.csdn.net/sc2079/article/details/83153693 - 写在前面 好久没更新博客了,主要还是最近 ...
- java动态代理框架
java动态代理是一个挺有意思的东西,他有时候可以被使用的很灵活.像rpc的调用,调用方只是定义的一个接口,动态代理让他匹配上对应的不同接口:mybatis内部的实现,编码时,只是实 ...
- SqlServer:SqlServer(存储过程动态表查询(取消返回值),事务处理,批量还原sqlserver备份,强制删除被占用的数据库)
1.存储过程动态表查询 USE [NETWORKING_AUDIT] GO /****** Object: StoredProcedure [dbo].[impConfigInfo] Script D ...
随机推荐
- linux学习笔记整理(九)
第十章 Centos7-系统进程管理本节所讲内容:10.1 进程概述和ps查看进程工具10.2 uptime查看系统负载-top动态管理进程10.3 前后台进程切换- nice进程优先级-实战scre ...
- mysql备份命令
mysql备份命令如下: 备份多个数据库可以使用如下命令: mysqldump -uroot -p123456 --databases test1 test2 test3 > /home/tes ...
- 20175329 2018-2019-3《Java程序设计》第三周学习总结
学号 20175329 2018-2019-3<Java程序设计>第三周学习总结 教材学习内容总结 第四章 第四章主要介绍JAVA中的类与对象的划分,其中有很多复杂的概念以及知识点需要花很 ...
- linux使用.net core 创建简单的MVC
1 创建MVC 2.修改默认绑定的端口方法 ,在Program.cs 的Build之前加入 .UseUrls("http://*:8888")
- vue 图片切换动态绑定
<img :src="切换条件 ? require('xxx.png') : require('xxx.png')" />
- hibernate(*.hbm.xml)中新添加的字段被标记为红色(找不到)的解决方法
首先得是以这个方式生成的bean和xml,配置好了数据源(这样才能让hibernate中的配置和mysql进行交互) https://www.cnblogs.com/kinome/p/10549969 ...
- Windows 10 配置Linux及安装Docker
https://baijiahao.baidu.com/s?id=1607159570058814753&wfr=spider&for=pc https://blog.csdn.net ...
- 小程序解决方案 Westore - 组件、纯组件、插件开发
数据流转 先上一张图看清 Westore 怎么解决小程序数据难以管理和维护的问题: 非纯组件的话,可以直接省去 triggerEvent 的过程,直接修改 store.data 并且 update,形 ...
- leveldb和fork的初始化顺序
我们服务器内用leveldb存一些不是很重要的, 但是又需要(半)持久化的东西. 可是自从2016到现在, 碰见好几次不同类型的死锁. 直到今天, 才发现真正的原因, 那就是leveldb不支持for ...
- python3 urllib及requests基本使用
在python中,urllib是请求url连接的标准库,在python2中,分别有urllib和urllib,在python3中,整合成了一个,称谓urllib 1.urllib.request re ...