为什么Spring-Data-JPA Async无法正常工作?

问题描述 投票:3回答:2

我正在尝试使用Spring Boot和Spring数据JPA创建一个非阻塞的休息服务。

如何使用Spring Data JPA @Async支持对实体进行异步保存。下面的代码对我来说不起作用,尽管其他选择似乎在同一个实体上工作。

我试图在JPA存储库中执行此操作。这是完整的存储库:除了保存。这些方法工作正常,我可以测试它们

public interface LoanRepository extends JpaRepository<Loan,Long> {

@Query("select distinct loan from Loan loan left join fetch loan.collaterals left join fetch loan.partys")
@Async
CompletableFuture<List<Loan>> findAllWithEagerRelationships();

@Query("select loan from Loan loan left join fetch loan.collaterals left join fetch loan.partys where loan.id =:id")
@Async
CompletableFuture<Loan> findOneWithEagerRelationships(@Param("id") Long id);

@Async
void delete(Long id);

}

但是,当我尝试添加以下保存方法时:

    @Async
    <S extends CompletableFuture<Loan>> S save(Loan loan);

我得到一个明显的编译错误,说"The method save(Loan) is ambiguous for the type LoanRepository"

我尝试将其更改为:

    @Async
    <S extends CompletableFuture<Loan>> S save(S loan);

但我在启动java.lang.UnsupportedOperationException: null时遇到异常,原因是:

Caused by: java.lang.NullPointerException: null
at org.springframework.data.repository.query.QueryMethod.potentiallyUnwrapReturnTypeFor(QueryMethod.java:244)

有关异步支持的Spring Data JPA文档在保存部分时尚不清楚。 Spring Data JPA Async Support

asynchronous spring-data-jpa spring-orm
2个回答
0
投票

您是否尝试过返回CompletableFuture?像这样(未经测试):

@Async
<S extends Loan> CompletableFuture<S> save(S loan);

你不能从JpaRepository扩展,因为这将与它继承自CrudRepository的那个发生冲突。从Repository扩展而来,并从CrudRepositoryPagingAndSortingRepositoryJpaRepository复制你需要的任何方法


0
投票

只是猜测:也许保存需要交易,而查询不需要。试试@Transactional ......

© www.soinside.com 2019 - 2024. All rights reserved.