利用Transactional 記錄刪除操作,無(wú)論成功與否都要記錄

準(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);

? ? ? ? }

? ? }

}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容