mybatis批量增加与删除——(十五)
1.首先应该明白,mybatis增删改返回值是int型的影响行数的值
mapper接口
package cn.xm.mapper; import java.util.List; import cn.xm.pojo.Questions; /**
* 自定义的批量删除与批量增加试题
* @author liqiang
*
*/
public interface QuestionsCustomMapper {
/**
* 批量导入试题
* @param list 需要倒入的试题集合
* @return
* @throws Exception
*/
public int saveQuestionBatch()throws Exception; }
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
<mapper namespace="cn.xm.mapper.QuestionsCustomMapper"> <insert id="saveQuestionBatch">
INSERT INTO `exam`.`questions`
VALUES ('7',
'1',
'测试题目7',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
"安全知识")
</insert> </mapper>
测试代码:
package cn.xm.test.mybatis; import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmxMBean;
import org.junit.Before;
import org.junit.Test; import cn.xm.mapper.EmployeeInMapper;
import cn.xm.mapper.QuestionsCustomMapper;
import cn.xm.pojo.EmployeeIn;
import cn.xm.pojo.EmployeeInExample; public class MybatisTest2 { private SqlSessionFactory sqlSessionFactory; @Before
public void setUp() throws Exception {
// 将全局配置文件作为一个流
String resource = "sqlMapConfig.xml";
String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
InputStream inputStream = Resources.getResourceAsStream(resource);
// 建立一个SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} // 测试增加
@Test
public void testAdd() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
int total = qsm.saveQuestionBatch();
System.out.println(total);
sqlSession.commit();
sqlSession.close();
} }
结果:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC8AAAAZCAIAAAAuZuBLAAAAhklEQVRIie3Wuw2AMAxF0TeXB/I8nsYVI7BBKhpGoH0UfBR+EgUEEL5yZUXKqaKAy5q2m8ermhfkBOjZItl6M4XbNdu7TQhhekRD0pVANnp0sIjmdKEJzT81yQQAdO/9KqtxBcRM36BxHQz+Ck2mCk1oQnOBZnz38sT2vk1FNHcXmtB8X9MDk7MwqzLmPsEAAAAASUVORK5CYII=" alt="" />
2.批量增加
sql语句: insert into xxx values ("xx1",'xxx1'),("xx2","xxx2"),("xx3","xxx3")
mapper接口
/**
* 批量导入试题
* @param list 需要倒入的试题集合
* @return 影响的行数
* @throws Exception
*/
public int saveQuestionBatch(List<Questions> list)throws Exception;
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
<mapper namespace="cn.xm.mapper.QuestionsCustomMapper"> <!-- INSERT INTO `exam`.`questions` VALUES ('7', '1', '测试题目7', NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, "安全知识") -->
<insert id="saveQuestionBatch" parameterType="java.util.List">
INSERT INTO `exam`.`questions`
VALUES
<foreach collection="list" item="question" separator=",">
(#{question.questionid},#{question.questionbankid},#{question.question},#{question.questionwithtag},#{question.answer},#{question.analysis},#{question.type},#{question.level},#{question.employeeid},#{question.uploadtime},#{question.status},#{question.knowledgetype})
</foreach>
</insert> </mapper>
测试代码:
package cn.xm.test.mybatis; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test; import cn.xm.bean.basebean.Questions;
import cn.xm.mapper.QuestionsCustomMapper; public class MybatisTest2 { private SqlSessionFactory sqlSessionFactory; @Before
public void setUp() throws Exception {
// 将全局配置文件作为一个流
String resource = "sqlMapConfig.xml";
String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
InputStream inputStream = Resources.getResourceAsStream(resource);
// 建立一个SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
// 测试批量增加
@Test
public void testBatchAdd() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
List<Questions> list = new ArrayList<>();
list.add(new Questions("8", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
list.add(new Questions("9", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
list.add(new Questions("10", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
list.add(new Questions("11", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
int total = qsm.saveQuestionBatch(list);
System.out.println(total);
sqlSession.commit();
sqlSession.close();
} }
总结:传入单个List上面SQL中collection名字应该是list,输入类型是List
3.批量删除
sql语句: DELETE FROM `exam`.`questions` WHERE `questionId` IN ('10','11','8','9')
java接口:
/**
* 批量删除
* @param ids id集合
* @return 删除条数
* @throws Exception
*/
public int deleteQuestionBatch(List<String> ids)throws Exception;
mapper.xml
<!-- 批量删除 -->
<!-- DELETE FROM `exam`.`questions` WHERE `questionId` in ('10','11','8','9') -->
<delete id="deleteQuestionBatch" parameterType="java.util.List">
DELETE FROM `exam`.`questions` WHERE `questionId` in
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
测试代码:
package cn.xm.test.mybatis; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test; import cn.xm.bean.basebean.Questions;
import cn.xm.mapper.QuestionsCustomMapper; public class MybatisTest2 { private SqlSessionFactory sqlSessionFactory; @Before
public void setUp() throws Exception {
// 将全局配置文件作为一个流
String resource = "sqlMapConfig.xml";
String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
InputStream inputStream = Resources.getResourceAsStream(resource);
// 建立一个SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} // 测试批量删除
@Test
public void testBatchDelete() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
List<String> ids = new ArrayList<>();
ids.add("8");
ids.add("9");
ids.add("10");
ids.add("11");
int total = qsm.deleteQuestionBatch(ids);
System.out.println(total);
sqlSession.commit();
sqlSession.close();
} }
4. 批量更新
需要在db链接url后面带一个参数 &allowMultiQueries=true
spring.datasource.url = jdbc:mysql://localhost:3306/fc?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
如下:
接口方法:
void updateUsers(List<User> users);
xml:
<update id="updateUsers" parameterType="list">
<foreach collection="list" separator=";" item="item">
update user
<trim prefix="set" suffixOverrides=",">
<if test="item.phone != null and item.phone != ''">
phone = #{item.phone},
</if>
<if test="item.roles != null and item.roles != ''">
roles = #{item.roles},
</if>
</trim>
<where>
<if test="item.id != null and item.id != ''">
id = #{item.id}
</if>
</where>
</foreach>
生成的SQL如下:
2019-09-12 11:23:32.397 DEBUG 16468 --- [nio-8088-exec-1] c.qs.mapper.user.UserMapper.updateUsers : ==> Preparing: update user set phone = ?, roles = ? WHERE id = ? ; update user set phone = ?, roles = ? WHERE id = ? ; update user set phone = ?, roles = ? WHERE id = ? ; update user set phone = ?, roles = ? WHERE id = ? ; update user set phone = ?, roles = ? WHERE id = ?
2019-09-12 11:23:32.397 DEBUG 16468 --- [nio-8088-exec-1] c.qs.mapper.user.UserMapper.updateUsers : ==> Parameters: 123123(String), 3(String), 1(Integer), 123123(String), 8(String), 2(Integer), 123123(String), 6(String), 3(Integer), 123123(String), 7(String), 4(Integer), 123123(String), 7(String), 5(Integer)
2019-09-12 11:23:32.613 DEBUG 16468 --- [nio-8088-exec-1] c.qs.mapper.user.UserMapper.updateUsers : <== Updates: 1
还有第二种case when 语句的批量更新,这种就不通用了。
mybatis批量增加与删除——(十五)的更多相关文章
- Spring+SpringMVC+MyBatis深入学习及搭建(十五)——SpringMVC注解开发(基础篇)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7065294.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十四)--S ...
- hibernate 批量增加 修改 删除
4.2 Hibernate的批量处理 Hibernate完全以面向对象的方式来操作数据库,当程序里以面向对象的方式操作持久化对象时,将被自动转换为对数据库的操作.例如调用Session的delete ...
- MyBatis批量添加和删除
一.批量插入 二.批量删除
- ABP 框架集成EF批量增加、删除、修改只针对使用mmsql的
AppService 层使用nuget 添加 EFCore.BulkExtensions 引用 using Abp.Application.Services.Dto; using Abp.Domain ...
- Mybatis批量添加,删除与修改
1.批量添加元素session.insert(String string,object O) public void batchInsertStudent(){ List<Student> ...
- mybatis 批量增加 Parameter '__frch_item_0' not found. Available parameters are [list]
当在mybatis用到foreach的时候,会报这个错误Parameter '__frch_item_0' not found. Available parameters are [list]会出现的 ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十六)——SpringMVC注解开发(高级篇)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7085268.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十五)——S ...
- FreeSql (十五)查询数据
FreeSql在查询数据下足了功能,链式查询语法.多表查询.表达式函数支持得非常到位. IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnect ...
- FreeSql (二十五)延时加载
FreeSql 支持导航属性延时加载,即当我们需要用到的时候才进行加载(读取),支持1对1.多对1.1对多.多对多关系的导航属性. 当我们希望浏览某条订单信息的时候,才显示其对应的订单详细记录时,我们 ...
随机推荐
- 11.10 Daily Scrum
工作进度有点拖后,之后几天要加快步伐了. Today's tasks Next week 丁辛 餐厅列表UI设计 餐厅列表事件处理 李承晗 实现指 ...
- java实验报告一
一.实验内容 1. 使用JDK编译.运行简单的Java程序 2.使用Eclipse 编辑.编译.运行.调试Java程序 二.实验步骤 (一)命令行下Java程序开发 1. 首先双击桌面上的Xface终 ...
- 20172319 《Java程序设计教程》第7周学习总结
20172319 2018.04.11-16 <Java程序设计教程>第7周学习总结 目录 教材学习内容总结 教材学习中的问题和解决过程 代码调试中的问题和解决过程 代码托管 上周考试错题 ...
- dispatch_block_t
通常我写一个不带参数的块回调函数是这样写的 在 . h 头文件中 定义类型 typedef void (^leftBlockAction)(); 在定义一个回调函数 -(void)leftButton ...
- CentOS7 如何修改 内核版本
1. 参考blog http://www.mamicode.com/info-detail-1758066.html https://www.cnblogs.com/sexiaoshuai/p/839 ...
- OneZero第五周第一次站立会议(2016.4.18)
1. 时间: 13:00--13:15 共计15分钟. 2. 成员: X 夏一鸣 * 组长 (博客:http://www.cnblogs.com/xiaym896/), G 郭又铭 (博客:http ...
- 600字让你读懂Git
设想你现在位于 alpha/ 目录下,这里有一个文本文件 number.txt,里面的内容只有一个词:“first”. 现在执行 git init 将这个 alpha 文件夹初始化为 Git 仓库. ...
- js写插件教程深入
原文地址:https://github.com/lianxiaozhuang/blog 转载请注明出处 js 写插件教程深入 1.介绍具有安全作用域的构造函数 function Fn(name){ t ...
- MT【168】还是两根法
设二次函数$f(x)=ax^2+bx+c(a>0)$,方程$f(x)=x$的两根$x_1,x_2$满足$0<x_1<x_2<\dfrac{1}{a}$,(Ⅰ)当$x\in(0, ...
- 【CH6201】走廊泼水节
题目大意:给定一棵树,要求增加若干条边,将其转化为完全图,且该完全图以该树为唯一的最小生成树,求增加的边权最小是多少. 题解:完全图的问题一般要考虑组合计数.重新跑一遍克鲁斯卡尔算法,每次并查集在合并 ...