【问题标题】:Does Spring Data Jpa supports repository inheritance and how to do?Spring Data Jpa 是否支持存储库继承以及如何做?
【发布时间】:2017-06-16 15:53:05
【问题描述】:

我有一个简单的实体继承树,由以下内容组成:

abstract class Item (id, ...)
class Chart extends Item (...)
class Table extends Item (...)

每个类都有自己的存储库:ItemRepositoryChartRepositoryTableRepository。所有三个存储库都公开

由于域规则,我需要在删除时实现自定义逻辑,如下所述:http://docs.spring.io/spring-data/jpa/docs/1.10.3.RELEASE/reference/html/#repositories.custom-implementations

此自定义删除逻辑涉及继承树中的所有实体(抽象实体和具体实体)。

有没有办法在ItemRepository 上实现自定义逻辑并使子实体的存储库扩展ItemRepository

这将避免为继承树的每个实体重复相同的逻辑。没有它,这会产生很多样板类:

EntityRepository + EntityRepositoryCustom + EntityRepositoryImpl x 3 entities = 9 classes 只是为了在删除时执行 1 ligne 的代码...

编辑

用户user7398104 的回答让我按照herethere 的解释实现了一些东西,但是这些资源没有解释如何在@NoRepositoryBean 基础存储库上实现自定义存储库。我没有运气尝试了以下方法:

@NoRepositoryBean
public interface ItemBaseRepository<T extends Item> extends 
    CrudRepository<T, Integer>,
    ItemBaseRepositoryCustom<T>

@RepositoryRestResource
public interface ItemRepository extends ItemBaseRepository<Item> {}

@RepositoryRestResource
public interface ChartRepository extends ItemBaseRepository<Item> {}

@RepositoryRestResource
public interface TableRepository extends ItemBaseRepository<Item> {}

public interface ItemBaseRepositoryCustom<T extends Item> {
    public void delete (T i);
}

public class ItemBaseRepositoryImpl<T extends Item>
    implements ItemBaseRepositoryCustom<T> {

    public void delete (T i) {
        // Custom logic
    }

}

编辑编辑

我尝试按照 cmets 的建议将 @NoRepositoryBean 设置为 ItemBaseRepositoryCustom,但它也不起作用。

【问题讨论】:

  • 来自官方 Spring Data Commons 参考:Custom implementations for Spring Data repositories
  • 嗨,谢谢,但这是我在我的问题上发布的同一个链接。我知道如何创建自定义存储库实现,但我被继承困住了。
  • 对不起@tiben - 该死的不专心! (
  • @Cepr0 不用担心
  • 您应该在问题中提及或描述您遇到的确切错误。

标签: java spring spring-data spring-data-jpa spring-data-rest


【解决方案1】:

您可以创建 ItemRepositoryCustom 接口来扩展 ItemRepository 接口,每个图表和表格存储库都扩展 ItemRepositoryCustom 存储库。对于此界面,您可以自定义实现删除操作。

编辑:我刚刚意识到这行不通。

但以下方法可行。

interface CustomItemRepository<T extends Item> extends CrudRepository<T, Long>{ }

interface ChartRepository extends CustomItemRepository<Chart>{ }

interface TableRepository extends CustomItemRepository<Table>{ }

然后您可以为 CustomItemRepository 创建一个删除逻辑的类。

【讨论】:

  • 我尝试了这个解决方案,但不幸的是它没有奏效。也许我做错了什么。我尝试使用ViewRepositoryCustom 接口、ViewRepositoryImpl 类,并且为了测试,使ChartRepository 接口扩展ViewRepositoryCustom。它只有在我专门化ViewRepositoryCustomViewRepositoryImpl 时才起作用,只需将它们重命名为ChartRepositoryCustomChartRepositoryImpl。所以我怀疑它是否适用于抽象实体类。
  • 嗨,您编辑的答案让我上路了,但我仍然无法实现自定义存储库。请参阅我对问题的编辑。
  • 不幸的是,这并没有改变任何东西。
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 2017-12-27
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
相关资源
最近更新 更多