在Spring Data JPA中处理实体继承的最佳方法 [英] Best way of handling entities inheritance in Spring Data JPA

查看:111
本文介绍了在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 应该是一个只读存储库(即扩展存储库类),而其他两个存储库应该公开所有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.

推荐答案

我使用了这篇文章

我们的想法是创建一个泛型存储库类,如下所示:

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> { /* ... */ }

此外,要获取<$的只读存储库c $ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆