首先要添加jar
包
在pom.xml
文件中添加
<!--spring-test-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
<scope>compile</scope>
</dependency>
然后在com.atguigu.crud.test
文件夹中创建MapperTest
测试文件
package com.atguigu.crud.test;
import com.atguigu.crud.bean.Employee;
import com.atguigu.crud.bean.EmployeeExample;
import com.atguigu.crud.dao.DepartmentMapper;
import com.atguigu.crud.dao.EmployeeMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* @author nyh
* @create 2018-08-17 13:37
**/
/*指定用哪个单元测试类来执行*/
@RunWith(value = SpringJUnit4ClassRunner.class)
/*@ContextConfiguration可以指定spring配置文件的位置,然后帮我们自动生成IOC容器*/
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Autowired
SqlSession sqlSession;
@Test
public void TestCRUD() {
/*往 dept表插入数据*/
// departmentMapper.insertSelective(new Department(null,"开发部"));
// departmentMapper.insertSelective(new Department(null,"测试部"));
/*往emp表插入数据*/
/*employeeMapper.insertSelective(new Employee(null,
"Jerry",
"M",
"Jerry@qq.com",
1));*/
/*批量插入数据*/
// EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
// for(int i=0;i<1000;i++){
// String uid = UUID.randomUUID().toString().substring(0, 5)+i;
// mapper.insertSelective(new Employee(null,uid,"M",uid+"@qq.com",1));
// }
// 查询emp表
List<Employee> employees = employeeMapper.selectByExample(new EmployeeExample());
for (Employee employee : employees) {
System.out.println(employee.toString());
}
System.out.println("查询完了");
}
}
上面批量插入数据的操作可以在applicationContext.xml
中配置一个配置一个可以执行批量的SqlSession
,方便以后的批量操作
<!--配置一个可以执行批量的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
重点是这两个注释
/*指定用哪个单元测试类来执行*/
@RunWith(value = SpringJUnit4ClassRunner.class)
/*@ContextConfiguration可以指定spring配置文件的位置,然后帮我们自动生成IOC容器*/
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})