首页 > 解决方案 > 处理异常时保存不起作用

问题描述

我面临着一种我什至找不到调试方法的情况。

我有以下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);
}

当集成运行正常时,将logOK状态一起保存。一切都很好。但是当我有异常时,由于某种原因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

谢谢!

标签: javahibernatespring-bootspring-data

解决方案


抛出的异常也是回滚集成日志保存。如果你想保存日志,你必须在保存时给它一个单独的事务。

将日志存储库抽象为服务,并在保存日志的服务方法上添加创建新事务的事务。

@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_CrudRepositorySimpleJpaRepository

@Transactional
public <S extends T> S save(S entity)

需要默认传播@Transactional

Propagation propagation() default Propagation.REQUIRED;

支持当前事务,如果不存在则创建一个新事务。

从上面的文档中可以看出,如果没有指定交易,它将创建一个新交易。因此,当您将业务层上的事务设置为NOT_SUPPORTED(非事务性执行)时,实际CrudRepository确实创建了它自己的事务,这意味着回滚不会影响它。


推荐阅读