在 Spring Data JPA 中处理实体继承的最佳方式 [英] Best way of handling entities inheritance in Spring Data JPA
问题描述
我有三个 JPA 实体 类 A
、B
和 C
,具有以下层次结构:>
I've three JPA entity classes A
, B
and C
with the following hierarchy:
A
|
+---+---+
| |
C B
即:
@Entity
@Inheritance
public abstract class A { /* ... */ }
@Entity
public class B extends A { /* ... */ }
@Entity
public class C extends A { /* ... */ }
使用Spring Data JPA,为此类实体编写存储库类的最佳方法是什么?
Using Spring Data JPA, what is the best way to write repositories classes for such entities?
我知道我可以写这些:
public interface ARespository extends CrudRepository<A, Long> { }
public interface BRespository extends CrudRepository<B, Long> { }
public interface CRespository extends CrudRepository<C, Long> { }
但是如果在 A
类中有一个字段 name
并且我在 ARepository
中添加了这个方法:
but if in the class A
there is a field name
and I add this method in the ARepository
:
public A findByName(String name);
我必须在其他两个存储库中也编写这样的方法,这有点烦人..有没有更好的方法来处理这种情况?
I've to write such method also in the other two repositories, and this is a bit annoying.. Is there a better way to handle such situation?
我想要的另一点是 ARespository
应该是一个只读存储库(即扩展 Repository
类),而其他两个存储库应该公开所有CRUD 操作.
Another point I would like to have is that ARespository
should be a read-only repository (i.e. extend the Repository
class) while the other two repositories should expose all the CRUD operations.
告诉我可能的解决方案.
Let me know possible solutions.
推荐答案
我使用了同样在 这篇文章 来自 Netgloo 的博客.
I used the solution also described in this post from Netgloo's blog.
这个想法是创建一个通用存储库类,如下所示:
The idea is to create a generic repository class like the following:
@NoRepositoryBean
public interface ABaseRepository<T extends A>
extends CrudRepository<T, Long> {
// All methods in this repository will be available in the ARepository,
// in the BRepository and in the CRepository.
// ...
}
那么我可以这样写三个仓库:
then I can write the three repositories in this way:
@Transactional
public interface ARepository extends ABaseRepository<A> { /* ... */ }
@Transactional
public interface BRepository extends ABaseRepository<B> { /* ... */ }
@Transactional
public interface CRepository extends ABaseRepository<C> { /* ... */ }
此外,要获得 ARepository
的只读存储库,我可以将 ABaseRepository
定义为只读:
Moreover, to obtain a read-only repository for ARepository
I can define the ABaseRepository
as read-only:
@NoRepositoryBean
public interface ABaseRepository<T>
extends Repository<T, Long> {
T findOne(Long id);
Iterable<T> findAll();
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
并且从 BRepository
还扩展 Spring Data JPA 的 CrudRepository
以实现读/写存储库:
and from BRepository
extend also the Spring Data JPA's CrudRepository
to achieve a read/write repository:
@Transactional
public interface BRepository
extends ABaseRepository<B>, CrudRepository<B, Long>
{ /* ... */ }
这篇关于在 Spring Data JPA 中处理实体继承的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!