[英]How to validate Spring Data JPA Queries on Startup?
給出一個Spring Data JPA Repository就好了。
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數據配置為在啟動時驗證查詢嗎?
我建議你創建一個可以由持續集成服務器執行的測試,而不是在啟動時驗證它。 由於您已經在使用Spring,因此創建可以使用已知測試數據初始化的嵌入式數據庫非常簡單。
創建兩個文件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
指定)。
您可以在bean上創建一個用@PostCreate
注釋修飾的方法,並調用存儲庫方法,以便立即發生任何異常。 如果你有很多,這很麻煩。
可能更合適的方法是對這些存儲庫方法進行單元測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.