mybatis学习笔记(12):Mybatis批量Insert
Mybatis提供两种⽅式进⾏批量插⼊操作
1. 使⽤foreach标签
foreach主要⽤在构建in条件中,它可以在SQL语句中迭代⼀个集合。
foreach元素的属性主要有:
item,index,collection,open,separator,close。
item表⽰集合中每⼀个元素进⾏迭代时的别名
index指 定⼀个名字,⽤于表⽰在迭代过程中,每次迭代到的位置
open表⽰该语句以什么开始
separator表⽰在每次进⾏迭代之间以什么符号作为分隔 符
close表⽰以什么结束
在使⽤foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不⼀样的,主要有⼀下3种情况:
如果传⼊的是单参数且参数类型是⼀个List的时候,collection属性值为list
如果传⼊的是单参数且参数类型是⼀个array数组的时候,collection的属性值为array
如果传⼊的参数是多个的时候,我们就需要把它们封装成⼀个Map了
具体⽤法如下:
<insert id="addEmp" parameterType="batis.domain.Employee">
insert into
tbl_employee(last_name,gender,email)
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{der},#{ail})
</foreach>
</insert>
这种⽅式是使⽤foreach 标签进⾏sql执⾏语句的拼接以达到批量插⼊的操作,
但是这种⽅式是由限制的,根据使⽤的数据库服务器的不同可执⾏的sql长度是由限制的,处理⼤批量的数据是请慎⽤这种⽅式。
2. mybatis的 ExecutorType.BATCH
Mybatis内置的ExecutorType有3种,默认的是simple,该模式下它为每个语句的执⾏创建⼀个新的预处理语句,单条提交sql;⽽batch 模式重复使⽤已经预处理的语句,并且批量执⾏所有更新语句,显然batch性能将更优; 但batch模式也有⾃⼰的问题,⽐如在Insert操作时,在事务没有提交之前,是没有办法获取到⾃增的id,这在某型情形下是不符合业务要求的。
2.1 将插⼊语句改为单条插⼊:
<insert id="addEmp" parameterType="batis.domian.Employee">
insert into
tbl_employee(last_name,gender,email)
values(#{lastName},#{gender},#{email})
</insert>
2.2 然后使⽤for循环反复执⾏:
@Test
public void addEmp(){
SqlSessionFactory sessionFactory = Factory();批量更新sql语句
//这⾥修改执⾏器的类型
SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);
EmployeeMapper mapper = Mapper(EmployeeMapper.class);
try {
long startTime = System.currentTimeMillis();
for(int i=0;i<10000;i++){
//造⼀些数据
String lastName = UUID.randomUUID().toString().substring(0,5);
mapper.addEmp(new Employee(lastName,"1",null));
}
sessionmit();
long endTime = System.currentTimeMillis();
/**
* BATCH⽅式⽤时:4573
* 普通⽅式⽤时:7069
*/
System.out.println("⽤时:"+(endTime-startTime));
} finally{
session.close();
}
}
在获取SqlSession时修改执⾏器为BATCH类型即可。
2.3 mybatis整合spring时配置⼀个SqlSessionTemplate
<bean id="sqlSessionTemplate"class="batis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory"ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType"value="BATCH"></constructor-arg>
</bean>
在spring容器中注册⼀个执⾏器为BATCH的sqlSession实例,然后在需要批量处理的地⽅引⼊这个SqlSession使⽤即可,

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。