企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**1. 在Spring配置文件`ApplicationContext.xml`中配置事务管理器** ```xml <!-- 1. 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 2. 开启事务注解--> <tx:annotation-driven transaction-manager="transactionManager" /> ``` **2. 在service层的方法上添加注解`@Transactional`开启事务** 你可以在接口方法上添加或者在接口实现类的方法上添加都可以。 ```java public interface StudentService { //在接口的方法上添加 @Transactional int batchInserts(List<Student> studentList); } ``` ```java @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override @Transactional //或者在接口实现类的方法上添加 public int batchInserts(List<Student> studentList) { for (int i = 0; i < studentList.size(); i++) { Student student = studentList.get(i); if (i == 4) { int d = 10 / 0; //除0异常 } studentDao.insert(student); } return studentList.size(); } } ``` **3. 测试事务效果** ```java @Test public void batchInserts() { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); StudentService studentService = context.getBean(StudentService.class); List<Student> studentList = new ArrayList<>(); studentList.add(new Student("李四", 20, "男")); studentList.add(new Student("王五", 21, "男")); studentList.add(new Student("赵六", 22, "男")); studentList.add(new Student("田七", 23, "男")); studentList.add(new Student("周八", 24, "男")); int result = studentService.batchInsert(studentList); System.out.println(result); } ``` 当插入第4条数据时发生除0异常,查看数据库没有被任何修改,事务配置成功。