Héctor
Héctor

Reputation: 26044

Understanding repositories in Spring Data

I want to create a "generic" repository that query data from multiple entities. If I do that:

@Repository
public interface MyRepository {

    @Query("select r from Role r")
    List<Role> getRoles();

}

I get an error because Spring doesn't find an implementation to inject when a MyRepository instance is required. So far, so good. Now, If I do this:

@Repository
public interface MyRepository extends JpaRepository {

    @Query("select r from Role r")
    List<Role> getRoles();

}

I get an error because Object is not a JPA managed type (JpaRepository is generic). Ok, again. If I do this:

@Repository
public interface MyRepository extends JpaRepository<User, String> {

    @Query("select r from Role r")
    List<Role> getRoles();

} 

It works. Why? I'm declaring a JpaRepository for entity User, not Role. Why does JpaRepository need a concrete entity even when the queries will be against another one?

Upvotes: 2

Views: 2805

Answers (1)

mlg
mlg

Reputation: 5756

Every repository in Spring Data has to extend the Repository interface, that is a generic interface, so you always have to specify the entity you are gonna work with and you can't do anything about it because it is how Spring Data is implemented. You can find more information here about creating repositories:

http://docs.spring.io/spring-data/jpa/docs/1.4.0.M1/reference/html/repositories.html

On the other hand, of course you can specify one entity to the repository and then add methods that return other type of entities because in your interface you can add whatever you want (also notice that Repository interface has no methods). But if you want to use the methods of the parent interface you have to use the entity you specified.

In your example, you could do what @M. Deinum suggested and create a JpaRepository<Role, Long> and use the findAll query, that makes much more sense. Using a JpaRepository<User, String> as you are doing is just a misuse of the framework.

Upvotes: 1

Related Questions