3

We are working on a Restful project with lots of DB tables. Though the operations on the tables are almost same and mainly INSERT/UPDATE/DELETE/FETCH.

my questions is:
will we have to create a repository (extending JpaRepository) for every entity (Domain class) we create or, there is an option of creating a GenericRepository that can handle all the above-mentioned functionalities for all the entities? i.e a single GenericRepository for all.

if so, could you share an example?

Sudipta Ghosh
  • 31
  • 1
  • 4
  • 1
    Spring Data JPA is intended to use with small number of entity types, quickly creating repositories for them. For common-type repository, you may create your own class, taking `EntityManager` from application context and delegating insert/update/delete methods to its `.persist()`, `.merge()` and `.remove()` methods – Alex Salauyou Jun 25 '18 at 11:49
  • Thanks a lot for clearing my doubts. – Sudipta Ghosh Jun 25 '18 at 15:17
  • About having a repository per entity: https://stackoverflow.com/questions/21265262/are-you-supposed-to-have-one-repository-per-table-in-jpa – Jens Schauder Nov 30 '18 at 13:58
  • Possible duplicate of [Using generics in Spring Data JPA repositories](https://stackoverflow.com/questions/19417670/using-generics-in-spring-data-jpa-repositories) – Jens Schauder Nov 30 '18 at 13:58

2 Answers2

7

is [there] an option of creating a GenericRepository that can handle all the above-mentioned functionalities for all the entities?

You are looking at this with a wrong assumption: You are really not supposed to have a repository per table/entity but per Aggregate(Root). See Are you supposed to have one repository per table in JPA? for more details.

Second: Having a generic repository kind of defies the purpose of Spring Data JPA, after all, JPA already has a generic repository. It's called EntityManager. So if you just need the operations you mentioned, just injecting an EntityManager should be fine. No need to use Spring Data JPA at all. And if you want to have something between your business code and JPA specifics, you can wrap it in a simple repository as described by @AlexSalauyou.

One final point: You'll have the code to create all the tables somewhere. You'll also have the code for all the entities. And you have the code for testing this. Is having a trivial interface definition for each going to be a problem?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
2

For insert/update/delete operations such repository may be as simple as:

@Component
public class CommonRepository {

  @PersistenceContext
  EntityManager em;

  @Transactional
  public <E> E insert(E entity) {
     em.persist(entity);
     return entity;
  }

  @Transactional
  public <E> E update(E entity) {
     return em.merge(entity);
  }

  @Transactional
  public void delete(Object entity) {
     em.remove(entity);
  }

}

For more accurate code, refer SimpleJpaRepository implementation

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67