💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 在Spring配置文件`ApplicationContext.xml`中配置事务管理器** ```xml <!-- 1. 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 2. 事务增强 --> <tx:advice id="txAdvice"> <!-- 3. 定义事务规则 --> <tx:attributes> <!-- 对所有以insert、batchInsert、del、update开头的方法添加事务 --> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="batchInsert*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 4. 定义切面 --> <aop:config> <!-- 5. 定义切入点 --> <aop:pointcut id="serviceMethod" expression="execution(* com.learn.spring07.service..*.*(..))" /> <!-- 6. 应用事务增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" /> </aop:config> ``` **2. 上面配置好后,在业务层中对应的方法就会有事务了** ```java @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public int batchInsert(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 batchInsert() { 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异常,查看数据库没有被任何修改,事务配置成功。