本文在SpringBoot2之整合Mybatis的基础上进行

7.1、整合事务7.1.1、mapper接口

    int deleteEmployeeById(int id);

7.1.2、mapper映射文件

            delete from t_emp where emp_id = #{id}    

7.1.3、业务层接口及实现类

package online.liaojy.service;/** * @author liaojy * @date 2023/12/25 - 6:31 */public interface EmployeeService {    int deleteEmployeeById(int id);}

注意:只要引入 spring-boot-starter-jdbc 启动器(详见6.1节),spring boot 便会自动配置好 DataSourceTransactionManager ;
因此,只需在方法(或者类)加上 @Transactional 注解,即可进行事务管理。

package online.liaojy.service.impl;import online.liaojy.mapper.EmployeeMapper;import online.liaojy.service.EmployeeService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/** * @author liaojy * @date 2023/12/25 - 6:33 */@Servicepublic class EmployeeServiceImpl implements EmployeeService {    @Autowired    private EmployeeMapper employeeMapper;    @Transactional    @Override    public int deleteEmployeeById(int id) {        // 删除一条数据        int rowsOfDelete = employeeMapper.deleteEmployeeById(id);        System.out.println("已成功删除"+rowsOfDelete+"行数据");        // 制造一个异常        int i = 1/0;        return rowsOfDelete;    }}

7.1.4、控制层方法

    @Autowired    private EmployeeService employeeService;    @RequestMapping("/deleteEmployeeById")    public String deleteEmployeeById(){        int i = employeeService.deleteEmployeeById(26);        return "删除成功";    }

7.1.5、测试效果

测试前的数据

测试时发生异常

测试后的数据没变化,说明事务回滚功能正常

7.2、整合AOP7.2.1、导入AOP启动器依赖

                            org.springframework.boot            spring-boot-starter-aop        

7.2.2、创建切面类

package online.liaojy.advice;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;/** * @author liaojy * @date 2023/12/25 - 6:51 */@Component@Aspect@Order(5)public class LogAdvice {    @Before("execution(* online.liaojy.service.*.*.*(..))")    public void beforeLog(JoinPoint joinPoint){        // 获取连接点所对应目标方法所在类的名称        String className = joinPoint.getSignature().getClass().getSimpleName();        // 获取连接点所对应目标方法的名称        String methodName = joinPoint.getSignature().getName();        System.out.println(className+"类的"+methodName+"方法开始执行了!");    }}

7.2.3、测试效果

本文来自博客园,作者:Javaer1995,转载请注明原文链接:https://www.cnblogs.com/Javaer1995/p/17925694.html