asynchronousspring-data-jpaspring-orm

Why is Spring-Data-JPA Async not working?


I am trying to create a non-blocking rest service with Spring Boot and Spring data JPA.

How to do Async save of an entity with Spring Data JPA @Async support. Below code is not working for me although other selects seem to be working on the same entity.

I am trying to do this within a JPA Repository. Here is full repository : except for save. These methods are working fine and I could test them

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

}

However, when I try to add the below save method :

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

I get an obvious compilation error which says "The method save(Loan) is ambiguous for the type LoanRepository"

I tried changing it to :

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

But I get an exception at startup java.lang.UnsupportedOperationException: null which is due to :

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

The Spring Data JPA Documentation on Async support is not clear on Save part of it. Spring Data JPA Async Support


Solution

  • I had this issue myself and after trying some variations this seems to work:

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