MyBatis_Mybatis之批量操作

1.引入

   MyBatis作为操作数据库的一个框架,批量操作是我们在开发中经常需要使用到的。下面我们就一起来学习一下如何使用MyBatis进行数据的批量操作。

2.如何使用MyBatis实现批量操作

我们之前学习过使用foreach遍历,然后通过不断的添加sql语句拼凑成一条较长的语句转给我们的数据库。如下:

<!-- 批量保存 -->
<!--public void addEmps(@Param("emps")List<Employee> emps);  -->
<!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
<insert id="addEmps">
	 insert into tbl_employee(
	 	<include refid="insertColumn"></include>
	 ) 
	 values
	<foreach collection="emps" item="emp" separator=",">
	  (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	</foreach>
</insert>

但是,我们发现这其实不是真正的实现了批量的操作,因为它其实就是把语句合并成为一条较长的语句,并没有达到批量的效果。如果我们要使用MyBatis实现数据的批量操作,那么我们应该使用的是:defaultExecutorType,内容如下:

3.批量操作的实现(添加操作测试)

(1).在映射文件中添加数据库添加的sql

<insert id="addUs" useGeneratedKeys="true" keyProperty="id">
		insert into tb_us(username,password) 
		values(#{username},#{password})
</insert>

(2).其他的相关操作不变。

(3).编写批量操作的相关代码

public void testBatch() throws IOException{
		
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		
		//可以执行批量操作的sqlSession
		SqlSession openSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
		long startTime = System.currentTimeMillis();
		try{
			UserMapper mapper = openSession.getMapper(UserMapper.class);
			for (int i = 0; i < 10000; i++) {
				mapper.addUs(new User(UUID.randomUUID().toString().substring(0, 5), 
                "1234"));
			}
			openSession.commit();
			long endTime = System.currentTimeMillis();
			System.out.println("操作时长:"+(endTime - startTime));
		}finally{
			openSession.close();
		}
}
	
	

(4).测试代码:

没有使用批量操作的时候执行1w条记录的插入操作使用:它的操作是:(预编译sql=设置参数=执行)==》10000    12161

使用批量操作:它的操作是:(预编译sql一次==>设置参数===>10000次===>执行(1次))

猜你喜欢

转载自blog.csdn.net/u013185175/article/details/113785243
今日推荐