我试图异步保存实体并返回结果的未来,但我遇到了以下问题:
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中以可调用的方式运行存储库方法
?