如何在启动时验证Spring Data JPA查询?

时间:2014-01-14 01:21:13

标签: java spring spring-data spring-data-jpa

给出一个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数据配置为在启动时验证查询吗?

2 个答案:

答案 0 :(得分:3)

我建议你不要在启动时验证这一点,而是建立一个可以由持续集成服务器执行的测试。由于您已经在使用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指定)。

答案 1 :(得分:0)

您可以在bean上创建一个用@PostCreate注释修饰的方法,并调用存储库方法,以便立即发生任何异常。如果你有很多,这很麻烦。

可能更合适的方法是对这些存储库方法进行单元测试。