Generic Repository in Spring JPA

烈酒焚心 提交于 2019-12-02 06:00:52

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?

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!