我尝试使用Sping Boot 构建一组CRUD REST API。我已经通过Spring Initializr创建了项目,依赖项为spring-boot-starter-data-couchbase。
我已经在这里上传了项目https://github.com/RosarioB/spring-boot-rest-api-couchbase-crud/tree/basic_crud测试类叫做CustomerRepositoryTest。
我使用CouchbaseTemplate实现了一些Repository方法。例如:
@Override
public List<Customer> findAll() {
List<JsonObject> jsonObjects = couchbaseTemplate.getCouchbaseClientFactory().getScope()
.query(String.format("SELECT * FROM %1$s ", keySpace)).rowsAsObject();
return jsonObjects.stream().map(this::mapJsonToCustomer).collect(Collectors.toList());
}
我还实现了对上述方法的测试(使用TestContainer):
@Test
public void testFindAll() {
Customer alex = new Customer("customer1", "Alex", "Stone");
Customer jack = new Customer("customer2", "Jack", "Sparrow");
List<Customer> customerList = List.of(alex, jack);
Transactions transactions = couchbaseTemplate.getCouchbaseClientFactory().getCluster().transactions();
customerList.forEach(customer ->
transactions.run(ctx -> ctx.insert(collection, customer.getId(), customer)
)
);
List<Customer> customers = customerRepository.findAll();
Assertions.assertEquals(customerList, customers);
}
我的问题是,即使我用collection.insert在数据库中执行插入2个项目,当我试图用customerRepository.findAll恢复项目时,有时测试失败,因为它只找到两个项目中的一个。
如果我在debug中运行测试,它就可以工作。我认为有一些同步问题,我试图同步的方法,但我没有解决这个问题。
我做错了什么?
1条答案
按热度按时间vom3gejh1#
您的服务类中缺少@Transactional annotation,
而且你正在破坏你的存储库类中的单一责任原则。
对于数据转换,创建Map器类(@Component)并在服务类中使用它们。
如果真的需要任何额外的配置,
你可以通过在'@Configuration'类中使用@Bean注解来注入适当的一个。
请注意,类级别的“@Transactional”注解仅适用于公共方法。
另一个问题是你的“GenericRepository”的不必要的实现,你应该扩展JpaRepository。
如果真的需要通用的,使用@NoRepositoryBean注解它。
根据JDBC transactions,请注意Spring Data保存和saveAndFlush方法之间的差异。https://www.baeldung.com/spring-data-jpa-save-saveandflush
有很多例子可以说明如何使用Spring Rest和Spring Data正确地实现一个项目。也许是众多中的一个:https://github.com/thevarga04/ucimsa