0

I have created an interface for Entity specific repository eg:

@Repository
public interface PlayerRepository extends CrudRepository<Player, Long> {
}

Is there way to create a generic repository so that i don't have to create repository entity per POJO, something of this sort:

@Repository
public interface PlayerRepository<T> extends CrudRepository<T, Long> {
}
dunni
  • 43,386
  • 10
  • 104
  • 99
Shubham Kumar
  • 167
  • 2
  • 3
  • 10
  • This might help you: 1) https://stackoverflow.com/questions/33511537/how-to-implement-generic-jpa-repository-in-spring-boot-which-can-be-autowired 2) https://stackoverflow.com/questions/54834170/how-to-make-a-generic-repository-in-spring-boot-that-accepts-an-entity-and-few-a 3) https://stackoverflow.com/questions/50493326/generic-jpa-repository-with-spring-boot – Nikita Kalugin Mar 16 '19 at 06:32

1 Answers1

1

I am afraid not. If you already tried you would have noticed that your second repository extending CrudRepository<T, Long> fails with something like:

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object.

because with generic T java can tell only that it is an Object which is not an entity. And because of that you need to add annotation @NoRepositoryBean which then only allows you to extend it with a real entity type instead of generic T.

It might be possible programmatically but most probably would be a lot more painful than just to create repo interfaces.

If you have entity inheritance tree like A->B->C you are able to create a repo for A that then handles also B & C what comes to properties inherited from A. So you could issue findAll() and it would return you all As, Bs & Cs but as a list of As and you would have to check the actual type of each item separately.

Usually when there is no need to any special treatment for entities and you do not want to write those repository "stubs" you can just use EntityManager directly. You can implement your own - generic repository like - @Service class that has @Autowired entity manager and invoke its find(..), persist(..) and other methods.

pirho
  • 11,565
  • 12
  • 43
  • 70