簡體   English   中英

Spring Data JPA-返回未來

[英]Spring Data JPA - return Future

我試圖保存我的實體異步並返回結果的未來,但是我遇到以下問題:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.Repository;
import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Repository;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

// I must extend Repository because when I extended JpaRepository an argument 
// of save is ambigous when I try save(countryEntity) - compiler shows me 
// save (CountryEntity) in AsyncCountryRepository and save (S) in CrudRepository
public interface AsyncCountryRepository extends Repository<CountryEntity, Long> {

    // I don't know why I cannot return Future<CountryEntity>
    @Async
    <S extends CountryEntity> Future<S> save(CountryEntity countryEntity);

    // I cannot test it - test is below
    @Async
    CompletableFuture<CountryEntity> findByCode(String code);

}


@RunWith(SpringRunner.class)
@DataJpaTest
public class CountryRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private AsyncCountryRepository countryRepository;

    @Test
    public void findByCodeTest() throws Exception {
        // given
        final CountryEntity countryEntity = new CountryEntity("EN");

        final CountryEntity persisted = entityManager.persist(countryEntity);
        entityManager.flush();

        // when
        final Future<CountryEntity> byCode = countryRepository.findByCode(persisted.getCode());

        // then
        assertThat(byCode.get())
                .isEqualTo(persisted);
    }

測試返回失敗,並且我得到了expected:<CountryEntity(id=1, code=EN)> but was:<null>

如何將我的存儲庫實現為異步存儲庫以及如何對其進行測試?

哪種方法具有更好的性能:1.從存儲庫返回期貨2.在ExecutorService中以Callable的身份運行存儲庫方法?

如果使用@Async則存儲庫代碼將在其自身事務中的單獨線程中運行。 由於您的原始交易未提交,因此看不到更改(即插入的實體),因此結果為null

因此,為了使其正常工作,您需要提交第一筆交易。

關於性能的第二個問題(下次請另外回答):多線程代碼的性能取決於很多事情,這實際上是回答它的唯一有用方法:嘗試一下。 但是,如果安排執行的方式對性能的影響比對線程池和連接池大小的影響更大,我會感到驚訝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM