【问题标题】:How do I map using spring JPA(Hibernate) for several tables referring to one table based on type and id?如何使用 spring JPA(Hibernate) 映射基于类型和 id 引用一个表的多个表?
【发布时间】:2018-04-14 16:59:21
【问题描述】:

我有一个遗留数据库设计,其中表 A、B、C 以 id 作为主键,并且它们都与表 D 具有一对多关系。表 D 具有 linkable_type 和 linkable_id 作为这些表的连接条件,即 A、B、 C.

其中 D.linkable_type ='A' 和 D.linkable_id = A.id

对于其他表也是如此,它被连接为 D.linkable_type ='B' 和 D.linkable_id = B.id D.linkable_type ='C' 和 D.linkable_id = C.id

我试过了

@ManyToOne
@JoinColumn(name="LINKABLE_ID", referencedColumnName="ID")
@WhereJoinTable(clause = " LINKABLE_TYPE = 'A' ")
private A a;

//bi-directional many-to-one association to TrainRoute
@ManyToOne
@JoinColumn(name="LINKABLE_ID", referencedColumnName="ID")
@WhereJoinTable(clause = " LINKABLE_TYPE = 'B' ")
private B b;

但由于同一列上有多个连接,它不起作用。 我也试过了

@ManyToOne
@Any(metaColumn = @Column(name = "LINKABLE_TYPE"))
@AnyMetaDef(idType = "long", metaType = "string",
        metaValues = {
                @MetaValue(targetEntity = A.class, value = "A"),
                @MetaValue(targetEntity = B.class, value = "B"),
                @MetaValue(targetEntity = C.class, value = "C")
        })
@Cascade( { org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name = "LINKABLE_ID", referencedColumnName = "ID")
@JsonProperty("linkable_id")
private E e;

我创造了

    public interface E {}

并在子类 A、B、C 中实现,但这不允许在 A 类中包含 @oneToMany 的反向关系,其中 Class 可以包含 D 列表。它找不到任何东西并失败。

      @OneToMany
      private List<D> d;

谁能帮助我如何使用 Hibernate 在 Spring JPA 中映射这些关系?

【问题讨论】:

标签: hibernate jpa hibernate-mapping polymorphic-associations


【解决方案1】:

我们通过以下方法解决了这个问题: 我们将@OneToMany 对象设为@Transient,并在保存父对象后手动保存该对象。这样我们就拥有了两个可用于映射的键。

在获取部分,我们可以在两列上使用 JPQL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2011-03-31
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多