java - 处理异常时保存不起作用
问题描述
我面临着一种我什至找不到调试方法的情况。
我有以下spring-data
存储库:
集成日志存储库
public interface IntegrationLogRepository extends PagingAndSortingRepository<IntegrationLog, Long> {
}
Foo存储库
public interface FooRepository extends PagingAndSortingRepository<Foo, Long> {
}
在我的业务逻辑上,我有以下内容:
IntegrationLog log = new IntegrationLog();
log.setTimestamp(new Date());
try {
Foo foo = new Foo();
// Build the Foo object...
fooRepository.save(foo);
log.setStatus("OK");
} catch (Exception e) {
log.setStatus("NOK");
} finally {
integrationLogRepository.save(log);
}
当集成运行正常时,将log
与OK
状态一起保存。一切都很好。但是当我有异常时,由于某种原因integrationLogRepository.save(log)
不会什么都不做。我什么都没有:没有抛出异常,我看不到任何休眠查询正在我的 WebLogic 控制台上执行。日志没有持久化...
关于为什么会发生这种情况的任何想法?
以下是我的依赖项:
compile 'org.springframework.boot:spring-boot-starter-data-rest'
compile 'org.springframework.boot:spring-boot-starter-security'
compile "org.springframework.boot:spring-boot-starter-web-services"
runtime 'org.springframework.boot:spring-boot-devtools'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile "org.springframework.boot:spring-boot-starter-websocket"
compile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'org.hibernate:hibernate-core:5.1.16.Final'
compile 'org.hibernate:hibernate-validator:5.2.3.Final'
compile 'org.hibernate:hibernate-entitymanager:5.1.0.Final'
在 Spring Boot 1.5.15.RELEASE
、Java1.7
和 WebLogic上运行12.1.3
。
谢谢!
解决方案
抛出的异常也是回滚集成日志保存。如果你想保存日志,你必须在保存时给它一个单独的事务。
将日志存储库抽象为服务,并在保存日志的服务方法上添加创建新事务的事务。
@Service
public class IntegrationLogService {
private final IntegrationLogRepository logRepository;
@Autowired
public IntegrationLogService(IntegrationLogRepository logRepository) {
this.logRepository = logRepository;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(Log log) {
this.logRepository.save(log);
}
}
在您的业务中替换
finally {
integrationLogRepository.save(log);
}
和
finally {
integrationLogService.save(log);
}
编辑
为什么@Transactional(propagation = Propagation.NOT_SUPPORTED)
在业务层上设置有效?
为了理解它为什么起作用,我们首先需要看看当一个人save
在 spring 中调用一个使用org.springframework.data.repository.CrudRepository
.
Spring 尝试确定TransactionAttribute
方法和 targetClass 上的 's。对于方法save
和类CrudRepository
,总之没有找到。Spring使用. SimpleJpaRepository
_CrudRepository
SimpleJpaRepository
@Transactional
public <S extends T> S save(S entity)
需要默认传播@Transactional
。
Propagation propagation() default Propagation.REQUIRED;
支持当前事务,如果不存在则创建一个新事务。
从上面的文档中可以看出,如果没有指定交易,它将创建一个新交易。因此,当您将业务层上的事务设置为NOT_SUPPORTED
(非事务性执行)时,实际CrudRepository
确实创建了它自己的事务,这意味着回滚不会影响它。
推荐阅读
- java - java swing中的按钮有问题
- sql-server - EF 6.1.3 异常 - 无法将“System.Data.Entity.Core.Objects.ObjectContext”类型的对象转换为“System.Data.Entity.DbContext”类型
- excel - 如何创建表的超链接?
- airflow - 气流 - 发送失败短信通知
- jenkins - 通过 ec2-plugin 以编程方式启动额外的 Jenkins 节点
- python - “来自通配符导入的未使用的导入操作系统”
- python-3.x - 使用 Dropbox API 和 python 列出文件夹和子文件夹中的所有文件
- try-catch - 尝试无例外
- algorithm - 无向图的深度优先搜索产生相同数量的树边
- java - 读取和写入 Firebase RT 不会更新 UI 或后端