问题
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