ssm整合Mybatis之批量操作

  • applicationContext-dao.xml中聲明一個可執行批量操作的sqlSession

通過構造函數注入方式:將SqlSessionTemplate交予Spring進行管理,方便後面service層中引用

注意:SqlSessionTemplate的executorType屬性爲BATCH

<!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 數據庫連接池 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 加載mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<!-- 掃描mapper.xml文件 -->
		<property name="mapperLocations" value="classpath:mapper/*.xml" />
	</bean>
	<!-- 執行批量操作的sqlsession  -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg  name="sqlSessionFactory" ref="sqlSessionFactory"/>
		<constructor-arg  name="executorType" value="BATCH"/>
	</bean>
  • service中使用該sqlSession:插入10000條數據測試

這裏需要注意@Transactional註解:讓spring對該方法進行事務管理

spring如何進行事務管理,這裏不做過多描述

@Service
public class DepartmentServiceImpl implements DepartmentService {
	private final static Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);
	//注入批量操作sqlSession
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	@Transactional
	public void batchSave() {
		//獲取Mapper
		DepartmentMapper mapper = sqlSessionTemplate.getMapper(DepartmentMapper.class);
		long start = System.currentTimeMillis();
		//插入10000條數據測試
		for(int i=0; i<10000;i++) {
			Department department = new Department();
			department.setDeptName(UUID.randomUUID().toString().substring(0, 4));
			mapper.saveDepartment(department);
		}
		long end = System.currentTimeMillis();
		logger.info("批量保存用時:"+(end-start));
	}
}
  • 對應的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">
<mapper namespace="com.li.mapper.DepartmentMapper">
	<insert id="saveDepartment" useGeneratedKeys="true" keyProperty="id">
		insert into tbl_dept(id,dept_name) values(#{id},#{deptName})
	</insert>
</mapper>
  • 測試結果:

只對參數進行預編譯,最後統一做保存處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章