Ybri
Ybri

Reputation: 603

Define a JPA Repository in the test folder Spring

I am creating a Spring library and to test it, I need to have Entities and Repositories that are defined only for the test folder.

When I create a Repository, it works well but as soon as I add a custom query to it, I have the error:

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!

Here is the structure of my test folder:

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

Here is the content of the repository:

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

Thank you for your help

Upvotes: 4

Views: 792

Answers (1)

narendra-choudhary
narendra-choudhary

Reputation: 4826

From Spring Data JPA - Reference Documentation: Query Creation docs:

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() does not fit this naming scheme. countAll() doesn't as well. You might ask then why findAll() works, or even getOne(ID) for that matter. findAll(), getOne(ID)( and other like existsById(ID), deleteAll()) methods are defined in CrudRepository, and probably resolved by additonal query resolver implementations.

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);
}

Upvotes: 3

Related Questions