利用Transactional 记录删除操作,无论成功与否都要记录

准备工作

1.创建数据库表 dept_log 日志表:

create table dept_log(

  id int auto_increment comment '主键ID' primary key,

    create_time datetime null comment '操作时间',

    description varchar(300) null comment '操作描述'

)comment '部门操作日志表';

2.引入实体类:DeptLog

@Data

@NoArgsConstructor

@AllArgsConstructor

public class DeptLog {

    private Integer id;

    private LocalDateTime createTime;

    private String description;

}

3.引入Mapper接口:DeptLogMapper

@Mapper

public interface DeptLogMapper {

    @Insert("insert into dept_log(create_time,description) values(#{createTime},#{description})")

    void insert(DeptLog log);

}

4.引入业务接口:DeptLogService

public interface DeptLogService {

    void insert(DeptLog deptLog);

}

5.引入业务实现类:DeptLogServiceImpl

@Service

public class DeptLogServiceImpl implements DeptLogService {

@Autowired

    private DeptLogMapper deptLogMapper;

@Transactional(propagation =Propagation.REQUIRES_NEW)

@Override

    public void insert(DeptLog deptLog) {

deptLogMapper.insert(deptLog);

}

}

代码实现:

业务实现类:DeptServiceImpl

@Slf4j

@Service

//@Transactional //当前业务实现类中的所有的方法,都添加了spring事务管理机制

public class DeptServiceImpl implements DeptService {

    @Autowired

    private DeptMapper deptMapper;

    @Autowired

    private EmpMapper empMapper;

    @Autowired

    private DeptLogService deptLogService;

    //根据部门id,删除部门信息及部门下的所有员工

    @Override

    @Log

    @Transactional(rollbackFor = Exception.class)

    public void delete(Integer id) throws Exception {

        try {

            //根据部门id删除部门信息

            deptMapper.deleteById(id);

            //模拟:异常

            if(true){

                throw new Exception("出现异常了~~~");

            }

            //删除部门下的所有员工信息

            empMapper.deleteByDeptId(id);

        }finally {

            //不论是否有异常,最终都要执行的代码:记录日志

            DeptLog deptLog = new DeptLog();

            deptLog.setCreateTime(LocalDateTime.now());

            deptLog.setDescription("执行了解散部门的操作,此时解散的是"+id+"号部门");

            //调用其他业务类中的方法

            deptLogService.insert(deptLog);

        }

    }

}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容