準(zhǔn)備工作
1.創(chuàng)建數(shù)據(jù)庫(kù)表 dept_log 日志表:
create table dept_log(
? id int auto_increment comment '主鍵ID' primary key,
? ? create_time datetime null comment '操作時(shí)間',
? ? description varchar(300) null comment '操作描述'
)comment '部門操作日志表';
2.引入實(shí)體類: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.引入業(yè)務(wù)接口:DeptLogService
public interface DeptLogService {
? ? void insert(DeptLog deptLog);
}
5.引入業(yè)務(wù)實(shí)現(xiàn)類: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);
}
}
代碼實(shí)現(xiàn):
業(yè)務(wù)實(shí)現(xiàn)類:DeptServiceImpl
@Slf4j
@Service
//@Transactional //當(dāng)前業(yè)務(wù)實(shí)現(xiàn)類中的所有的方法,都添加了spring事務(wù)管理機(jī)制
public class DeptServiceImpl implements DeptService {
? ? @Autowired
? ? private DeptMapper deptMapper;
? ? @Autowired
? ? private EmpMapper empMapper;
? ? @Autowired
? ? private DeptLogService deptLogService;
? ? //根據(jù)部門id,刪除部門信息及部門下的所有員工
? ? @Override
? ? @Log
? ? @Transactional(rollbackFor = Exception.class)
? ? public void delete(Integer id) throws Exception {
? ? ? ? try {
? ? ? ? ? ? //根據(jù)部門id刪除部門信息
? ? ? ? ? ? deptMapper.deleteById(id);
? ? ? ? ? ? //模擬:異常
? ? ? ? ? ? if(true){
? ? ? ? ? ? ? ? throw new Exception("出現(xiàn)異常了~~~");
? ? ? ? ? ? }
? ? ? ? ? ? //刪除部門下的所有員工信息
? ? ? ? ? ? empMapper.deleteByDeptId(id);
? ? ? ? }finally {
? ? ? ? ? ? //不論是否有異常,最終都要執(zhí)行的代碼:記錄日志
? ? ? ? ? ? DeptLog deptLog = new DeptLog();
? ? ? ? ? ? deptLog.setCreateTime(LocalDateTime.now());
? ? ? ? ? ? deptLog.setDescription("執(zhí)行了解散部門的操作,此時(shí)解散的是"+id+"號(hào)部門");
? ? ? ? ? ? //調(diào)用其他業(yè)務(wù)類中的方法
? ? ? ? ? ? deptLogService.insert(deptLog);
? ? ? ? }
? ? }
}