Spring JPA 存储库条件重载 joinColumn 实现

Spring JPA repository conditional overloaded joinColumn implementation

我这里有一部分数据库,针对以下问题进行了简化:

Supplier
  company_id    int
  location      String

Warehouse
  warehouse_id  int
  location      String

Store
  store_id      int
  location      String

Shipment
  shipment_id      int
  origin_id        int
  destination_id   int

Objective:系统用于记录和跟踪供应商与仓库之间、仓库与商店之间以及商店与商店之间的运输。

所以最初我计划通过创建 3 个 table 来实现这一点,每个存储一种类型的货物,但我意识到我可以通过创建一个名为 shipment 的 table 来抽象它,因为所有可能的起点和终点具有相同的长度和 id 类型(整数)。我使用 shipment.type 来识别来源是供应商、仓库还是商店,反之亦然 dest_type。我的问题是如何在 JPA 实体中实现它?我目前的伪代码是这样的:

@Entity
@Table(name = "SHIPMENT")
public class Shipment implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "SHIPMENT_ID")
    private int shipmentId;

    @Column(name = "ORIGIN_TYPE")
    private int originType;

    @Column(name = "DESTINATION_TYPE")
    private int destination_id;

    if(origin_type==1){
        @ManyToOne
        @JoinColumn(name = "ORIGIN_ID", nullable = false)
        private Supplier supplier;
    }
    else if(origin_type==2){
        @ManyToOne
        @JoinColumn(name = "ORIGIN_ID", nullable = false)
        private Warehouse warehouse;
    }
    else if(origin_type==3){
        @ManyToOne
        @JoinColumn(name = "ORIGIN_ID", nullable = false)
        private Store store;
    }
//same for destinations
}

我不知道这是否可能?而且我不知道要搜索什么关键字来执行此操作,因为我是自学的。

这种情况可以由 Inheritance MappingTable per class 处理。

The Table Per Class strategy maps each entity to its table which contains all the properties of the entity, including the ones inherited.

您需要将 SupplierWarehouseStore class 作为 Shipment 的子 class。并使用@Inhertance 您的 Shipment class 注释如下。

@Entity
@Table(name = "SHIPMENT")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Shipment implements Serializable

Here 就是一个例子。

已编辑答案

实际上,您的案例大部分符合 Joined Table

为此,您需要将继承类型更改为 @Inheritance(strategy = InheritanceType.JOINED)