(Spring/JpaRepository ) Inheriting methods of JpaRepository from BaseEntityRepository to SubEntityRepository

自作多情 提交于 2021-01-28 18:26:32

问题


What would be the best practice for the following case?

You have the following entities:

@Entity public class BaseEntity { }
@Entity public class SubEntity extends BaseEntity { }

And you have a JpaRepository for BaseEntity having multiple select-methods:

public interface BaseEntityRepository extends JpaRepository<BaseEntity, Long> {
  Set<BaseEntity> findAll();
  Set<BaseEntity> findSome...();
}

Now you want a JpaRepository for SubEntity inheriting all the methods from BaseEntityRepository.

Now I imagine multiple scenarios, from whom I am not sure which one is the best or which ones should work:

(a) Create a new independent JpaRepository for SubEntity with exactly the same Methods, but substituing BaseEntity with SubEntity:

public interface SubEntityRepository extends JpaRepository<SubEntity, Long> {
  Set<SubEntity> findAll();
  Set<SubEntity> findSome...();
}

(b) Extending BaseEntityRepository, all Methods should be inherited, but it still return BaseEntity-objects instead of SubEntity-objects

public interface SubEntity extends BaseEntityRepository {
}

I don't really like any of both solutions. How would you solve this?

Somehow I think JpaRepository is not ment for this use-case?


回答1:


You could parameterize your BaseEntityRepository and operate on those parameters.

public interface BaseEntityRepository<T, I> extends JpaRepository<T, I> {
  Set<T> findAll();
  Set<T> findSome...();
}

Then add any additional methods in the subclass by extending the BaseEntityRepository

public interface SubEntityRepository extends BaseEntityRepository<SubEntity, Long> {
  ...
}


来源:https://stackoverflow.com/questions/61426292/spring-jparepository-inheriting-methods-of-jparepository-from-baseentityrepos

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