动态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用户管理本节所讲内容:6.1 用户和组的相关配置文件6.2 管理用户和组6.3实战:进入centos7 紧急模式恢复root密码 用户一般来说是指使用计算机的人,计算机对针使用其 ...
- UltraISO制作Ubuntu14.04 64bit到U盘文件载入不完整
版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/zinss26914/article/details/37728251 前言 今天新买的Thinkpa ...
- SpringBoot实战之SpringBoot自动配置原理
SpringBoot 自动配置主要通过 @EnableAutoConfiguration, @Conditional, @EnableConfigurationProperties 或者 @Confi ...
- GT常见问题
1.需要root? 大部分核心功能都需要root权限.需要root的功能有:FPS.Mem Assistant.Logcat日志.抓包.流畅度获取(未开放). 2.root工具总弹出提示框要确认roo ...
- odoo11 systemd service自动启动配置
在ubuntu 16.04的环境下配置odoo11 跟随系统开机时自动启动的配置步骤: 1.在/etc/systemd/system/目录下建立odoo11.service文件 cd /etc/sys ...
- [Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子
[Spark][Python][DataFrame][RDD]DataFrame中抽取RDD例子 sqlContext = HiveContext(sc) peopleDF = sqlContext. ...
- bootstrap 失效的原因
首先必须对着官方文档的模板来写: https://getbootstrap.com/docs/4.3/getting-started/introduction/ 然后: 这里必须加上 rel=&quo ...
- 史上最全面的Spring Boot Cache使用与整合
一:Spring缓存抽象 Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口 ...
- gohost -- go 开发的命令行hosts配置管理工具
前几天在微博上看到有人推荐了lazygit这个工具,让人眼前一亮,什么时候命令行也可以这么抢到了,
- Intellij IDEA创建的Web项目配置Tomcat并启动Maven项目
本篇博客讲解IDEA如何配置Tomcat. 大部分是直接上图哦. 点击如图所示的地方,进行添加Tomcat配置页面 弹出页面后,按照如图顺序找到,点击+号 tomcat Service -> L ...