在测试文件夹中定义一个 JPA 存储库 Spring

Define a JPA Repository in the test folder Spring

我正在创建一个 Spring 库并对其进行测试,我需要 仅为测试文件夹 .[=14= 定义的实体和存储库]

当我创建一个存储库时,它运行良好,但是一旦我向它添加自定义查询,我就会遇到错误

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List package.ExampleRepository.getAll()! No property getAll found for type Example!

这是我的测试文件夹的结构:

test
  package
    Application (@SpringBootApplication)
    Example (@Entity)
    ExampleRepository (@Repository)
    Test (@SpringBootTest)

存储库的内容如下:

@Repository
public interface ExampleRepository extends JpaRepository<Example, Long> {
    List<Example> getAll();
}

感谢您的帮助

来自 Spring Data JPA - Reference Documentation: Query Creation 文档:

The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it.

getAll() 不适合这个命名方案。 countAll() 也不是。那么您可能会问为什么 findAll() 有效,甚至 getOne(ID) 就此而言。 findAll()getOne(ID)(和其他类似existsById(ID)deleteAll())方法在CrudRepository中定义,可能已解决通过额外的查询解析器实现。

public interface ExampleRepository extends JpaRepository<Example, Long> {

    // valid (resolvable)
    List<Example> findAll();

    //invalid (un-resolvable)
    List<Example> getAll();

    // valid
    Example getOne(Long id);

    // valid
    List<Example> getByName(String name);

    // invalid
    long countAll();

    //valid
    long countByName(String name);
}