2026/09/07笔记

事务的使用:

一、@Transactional 注解:

AOP代码实现的:在调用this.syncLocal(incoming))方法的前后,开启和提交事务。

调用方

→ Spring 代理对象.method()

→ 拦截器:开启事务

→ 真正执行目标方法

→ 拦截器:提交 / 回滚

二、transactionTemplate (精细化给某段代码加事务控制)

TransactionTemplate 是编程式开启,不依赖代理,私有方法里也能用。

  1. TransactionManager.getTransaction() // 开启事务、绑定到当前线程

  2. 执行 syncLocal(...) // 里面的 JDBC/MyBatis 自动加入这个事务

  3. commit(成功)或 rollback(异常)

@Override

public void fullSync() {

SingleCellDataPermissionHelper.ignore(() -> {

List<CellSingleLimsTrialGroup> incoming = loadFromLims();

if (CollectionUtils.isEmpty(incoming)) {

throw new ServiceException("LIMS部门数据为空,终止同步");

}

transactionTemplate.executeWithoutResult(status -> syncLocal(incoming));

cellSingleLimsTrialGroupTreeCache.refresh();

});

}

//不能使用@Transactional注解会失效

private void syncLocal(List<CellSingleLimsTrialGroup> incoming) {

Map<Long, CellSingleLimsTrialGroup> incomingMap = toIdMap(incoming);

Map<Long, CellSingleLimsTrialGroup> existingMap = toIdMap(cellSingleLimsTrialGroupDao.selectAllKeys());

List<CellSingleLimsTrialGroup> toInsert = new ArrayList<>();

List<CellSingleLimsTrialGroup> toUpdate = new ArrayList<>();

List<Long> toDelete = new ArrayList<>();

for (Map.Entry<Long, CellSingleLimsTrialGroup> entry : incomingMap.entrySet()) {

if (existingMap.containsKey(entry.getKey())) {

toUpdate.add(entry.getValue());

} else {

toInsert.add(entry.getValue());

}

}

for (Map.Entry<Long, CellSingleLimsTrialGroup> entry : existingMap.entrySet()) {

if (!incomingMap.containsKey(entry.getKey())) {

toDelete.add(entry.getKey());

}

}

if (CollectionUtils.isNotEmpty(toDelete)) {

cellSingleLimsTrialGroupDao.deleteByIds(toDelete);

}

if (CollectionUtils.isNotEmpty(toUpdate)) {

cellSingleLimsTrialGroupDao.updateByIds(toUpdate);

}

if (CollectionUtils.isNotEmpty(toInsert)) {

cellSingleLimsTrialGroupDao.insertBatch(toInsert);

}

log.info("检测部门树全量同步完成, incoming={}, insert={}, update={}, delete={}",

incomingMap.size(), toInsert.size(), toUpdate.size(), toDelete.size());

}

相关推荐
咖啡忍者7 小时前
【SAP BASIS】Section 5: SAP System Configuration
笔记
一隅论数智6 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
深圳老胡6 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
Because_of_Her16 天前
并查集-听课笔记
笔记·算法·并查集
彧azz6 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
陈卫军老师6 天前
陈卫军:把口味写在一张纸上,店才稳得住
经验分享·笔记·流量运营
`流年づ6 天前
人工智能学习笔记 - 补充
人工智能·笔记·深度学习·学习
qeen876 天前
【Linux】操作系统之进程介绍(二)
linux·笔记·学习·进程
从零开始的嵌入式之旅6 天前
day47
arm开发·经验分享·笔记·嵌入式硬件
陈年老古董6 天前
MediaPipe 姿态检测与脸部关键点检测
笔记·python·opencv·学习·dlib