【问题标题】:Spring JPA repository conditional overloaded joinColumn implementationSpring JPA 存储库条件重载 joinColumn 实现
【发布时间】:2021-02-05 02:23:34
【问题描述】:

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

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

目标:该系统用于记录和跟踪供应商与仓库之间、仓库与商店之间以及商店之间的发货。

所以最初我计划通过创建 3 个表来实现这一点,每个表存储一种类型的货物,但我意识到我可以通过创建一个名为 shipping 的表来抽象这一点,因为所有可能的起点和目的地都具有相同的长度和类型( int) 的 ID。我使用 shipping.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
}

我不知道这是否可能?而且我不知道要搜索什么关键字才能做到这一点,因为我正在自学。

【问题讨论】:

    标签: hibernate jpa hibernate-mapping


    【解决方案1】:

    此案可由Table per classInheritance Mapping 处理。

    Table Per Class 策略将每个实体映射到它的表,该表包含实体的所有属性,包括继承的属性。

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

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

    Here 就是一个例子。

    已编辑答案

    其实你的case大部分都符合Joined Table

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

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2016-12-30
      • 2017-08-20
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2022-01-25
      相关资源
      最近更新 更多