问题描述
以下情况的最佳做法是什么?
What would be the best practice for the following case?
您有以下实体:
@Entity public class BaseEntity { }
@Entity public class SubEntity extends BaseEntity { }
并且您有一个用于 BaseEntity 的 JpaRepository,具有多个选择方法:
And you have a JpaRepository for BaseEntity having multiple select-methods:
public interface BaseEntityRepository extends JpaRepository<BaseEntity, Long> {
Set<BaseEntity> findAll();
Set<BaseEntity> findSome...();
}
现在您需要一个 JpaRepository 用于继承 BaseEntityRepository 的所有方法的 SubEntity.
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) 使用完全相同的方法为 SubEntity 创建一个新的独立 JpaRepository,但用 SubEntity 替换 BaseEntity:
(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) 扩展 BaseEntityRepository,所有方法都应该被继承,但它仍然返回 BaseEntity-objects 而不是 SubEntity-objects
(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?
不知何故,我认为 JpaRepository 不适合这个用例?
Somehow I think JpaRepository is not ment for this use-case?
推荐答案
您可以参数化您的 BaseEntityRepository
并对这些参数进行操作.
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...();
}
然后通过扩展 BaseEntityRepository
public interface SubEntityRepository extends BaseEntityRepository<SubEntity, Long> {
...
}
这篇关于(Spring/JpaRepository) 从 BaseEntityRepository 到 SubEntityRepository 继承 JpaRepository 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!