给定一个像这样的 Spring Data JPA 存储库。
public interface ProductRepository extends CrudRepository<Product, Long>, QueryDslPredicateExecutor<Product> {
@Query("select p from Product p where p.attributes[?1] = ?2")
List<Product> findByAttributeAndValue(String attribute, String value);
}
如何让 Spring Data JPA 在启动时验证每个查询。例如,当我在 hibernate 中使用命名查询并且查询在语法上不正确或属性名称错误时,hibernate 会提示。
Spring Data 可以配置为在启动时验证查询吗?
最佳答案
我建议您为此创建一个可以由持续集成服务器执行的测试,而不是在启动时验证这一点。由于您已经在使用 Spring,因此创建 Embedded Database 非常简单。您可以使用已知的测试数据进行初始化。
创建两个文件schema.sql
(它是实际的生产数据模式)和test-data.sql
(其中包含一些已知的测试数据)。接下来,创建一个单独的测试应用程序上下文:
<beans ...>
<jpa:repositories base-package="com.example.repositories" />
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
<tx:annotation-driven/>
<!-- more beans -->
</beans>
或基于Java的配置:
@Configuration
@EnableJpaRepositories("com.example.repositories")
@EnableTransactionManagement
public class TestConfig {
@Bean(destroyMethod = "shutdown")
public void EmbeddedDatabase embeddedDatabase() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(H2).addScript("schema.sql").addScript("test-data.sql").build();
// more beans
}
接下来,为 ProductRepository
创建测试:
@ContextConfiguration([reference to your xml or Java application context])
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ProductRepositoryTest {
@Autowired
ProductRepository repository;
@Test
public void findProductByAttributeAndValue() {
List<Product> actual = repository.findByAttributeAndValue("attr", "val");
// add assertions that 'actual' contains the expected data from the test-data.sql
}
}
在测试类中添加@Transactional
将导致数据库在每个测试方法完成后自动回滚。因此,即使在测试中执行存储库写入操作,所有测试也将具有相同的数据库状态(由 test-data.sql
指定)。
关于java - 如何在启动时验证 Spring Data JPA 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21104504/