AndreaNobili
AndreaNobili

Reputation: 42957

Can I have a single JPA repository interface handling multiple entity classes using Spring Data JPA?

I am not so into Spring Data JPA and I have the following problem working on a Spring Boot project.

I have the following architectural doubt about how to correctly handle this kind of situation:

I have a repository implemented by an interface like this in which I am defining my "query methods":

public interface ExcelRepository extends CrudRepository<Country, Integer> {
    
    public List<Country> findAllByOrderByCountryNameAsc();

    public List<BlockAttackDetail> findAllByOrderByAttackTypeAcronymAsc();
}

As you can see I am extending the CrudRepository interface and I specified a single model class named Country mapping a specific table on my database.

I added a second method working on another entity class (BlockAttackDetail) mapping a different database table.

So starting my application I obtain this error because this repository is intended only for the database table mapped by the Country entity class:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property attackTypeAcronym found for type Country!

My problem is: Do I have to create multiple JPA repositories interfaces (one for each entity) or exist a way to have a single JPA repository interface working on multiple entity classes?

In my specific case I will have few methods that will interact with a specific datbase table (with an entity) and I prefear have a single repository interface handling multiple entity classes (to avoid confusion).

Can I do it in some way? And if I can do it make it sense from an architectural point of view or it is better have a specific JPA repository interface for each entity class?

Upvotes: 4

Views: 8140

Answers (1)

Dmitrii Cheremisin
Dmitrii Cheremisin

Reputation: 1568

According to Spring Data documentation you should have one repository for each entity

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.definition

In your case the only way to do your job is with Spring Data JPA:

public interface CountryRepository extends CrudRepository<Country, Integer> {

   public List<Country> findAllByOrderByCountryNameAsc();
}

public interface BlockAttackDetailRepository extends CrudRepository<BlockAttackDetail, Integer> {

   public List<BlockAttackDetail> findAllByOrderByAttackTypeAcronymAsc();
}

Upvotes: 8

Related Questions