基于注解方式的声明式事务
一、需求分析
掌握基于注解方式的声明式事务实现
二、编码实现
1、数据库环境
mybatis数据库,t_employee表
2、新建项目
引入pom.xml文件,导入applicationContext.xml、db.properties、log4j.properties、mybatisConfig.xml
3、数据封装类
com.sw.pojo包,Employee类
@Data
public class Employee {
private int id;
private String name;
private int age;
private String position;
}
4、mapper层
com.sw.mapper包,EmployeeMapper接口
public interface EmployeeMapper {
int insertOne(Employee employee);
}
com/sw/mapper目录,EmployeeMapper.xml文件
<insert id="insertOne" parameterType="com.sw.pojo.Employee">
insert into t_employee set name=#{name},age=#{age},position=#{position}
</insert>
5、service层
com.sw.service包,EmployeeService接口
public interface EmployeeService {
int insertList(List<Employee> employeeList);
}
com.sw.service.impl包,EmployeeServiceImpl类
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Resource
private EmployeeMapper employeeMapper;
public int insertList(List<Employee> employeeList) {
if (employeeList==null){
return 0;
}
if (employeeList.size()==0){
return 0;
}
for (int i = 0; i < employeeList.size(); i++) {
if (i==1){
throw new RuntimeException("模拟运行时异常");
}
employeeMapper.insertOne(employeeList.get(i));
}
return employeeList.size();
}
}
6、配置Spring
resources目录,applicationContext.xml
1)配置事务管理器
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
2)配置事务注解
<!--配置事务注解-->
<tx:annotation-driven/>
7、添加事物注解
com.sw.service.impl包,EmployeeServiceImpl类的insertList方法
@Transactional
public int insertList(List<Employee> list)
8、测试
com.sw.service包,EmployeeService接口的insertList方法,右键→Generate→Test
private EmployeeService employeeService;
@Before
public void setUp() throws Exception {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
employeeService = applicationContext.getBean("employeeServiceImpl", EmployeeService.class);
}
@Test
public void insertList() {
List<Employee> employeeList = new ArrayList<Employee>();
Employee employee1 = new Employee();
employee1.setName("a1");
employee1.setAge(11);
employee1.setPosition("员工");
Employee employee2 = new Employee();
employee2.setName("a2");
employee2.setAge(22);
employee2.setPosition("员工");
Employee employee3 = new Employee();
employee3.setName("a3");
employee3.setAge(33);
employee3.setPosition("员工");
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
int res = employeeService.insertList(employeeList);
if (res>0){
System.out.println("批量插入成功,共插入"+res+"条数据");
}else {
System.out.println("批量插入失败");
}
}