代码之家  ›  专栏  ›  技术社区  ›  user

春季数据JPA-回归未来

  •  2
  • user  · 技术社区  · 7 年前

    我试图异步保存实体并返回结果的未来,但我遇到了以下问题:

    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>

    如何将我的存储库实现为异步存储库,以及如何测试它?

    哪种方法性能更好: 2.在ExecutorService中以可调用的方式运行存储库方法 ?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jens Schauder    7 年前

    如果您使用 @Async null 后果

    因此,为了使其工作,您需要提交第一个事务。

    关于性能的第二个问题(请下次单独提问):多线程代码的性能取决于很多事情,而这实际上是唯一有用的回答方法:尝试一下。但是,如果调度执行的方式对性能的影响大于线程池和连接池大小,我会感到惊讶。