1、测试环境
1.1 pom文件引入spring测试用的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
1.2 在测试类中添加注解
使用runwith加载spring的测试类
ContextConfiguration指定springbean的加载配置文件
@RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(locations= {"classpath:/spring/spring-context.xml"})
1.3 使用spring的@autowired注解测试项目和数据库
2、批量插入
2.1 修改spring配置文件
<!-- 批量插入 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index = "0" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg index = "1" value="BATCH"></constructor-arg>
</bean>
SqlSessionTemplate中的构造方法,index对应SqlSessionFactory
和ExecutorType
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
this(sqlSessionFactory, executorType,
new MyBatisExceptionTranslator(
sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
}
测试方法中
/* 批量插入 */
List<Employee> list = new ArrayList<Employee>();
list.add(new Employee(null, "lee1", "123456", 23, null, "0", 1));
list.add(new Employee(null, "lee2", "123456789", 23, null, "1", 2));
list.add(new Employee(null, "lee3", "123456789101", 23, null, "0", 1));
/* 方法一 推荐*/
EmployeeMapper mapper = sqlsession.getMapper(EmployeeMapper.class);
for (Employee employee : list) {
mapper.insert(employee);
}
/* 方法二 */
for (Employee employee : list) {
sqlsession.insert("com.lee.dao.EmployeeMapper.insert", employee);
}