【问题标题】:Remove duplication in OneToMany/ManyToOne bidirectional relationship using a JoinTable (with an OrderColumn)使用 JoinTable(带有 OrderColumn)删除 OneToMany/ManyToOne 双向关系中的重复
【发布时间】:2011-05-23 18:39:21
【问题描述】:

我有一个使用连接表的 OneToMany/ManyToOne 双向关系。孩子们在一个列表中并且是有序的。

设置如下:

家长:

@OneToMany(cascade=CascadeType.ALL)
@JoinTable(
    name="parent_child",
    joinColumns=@JoinColumn(name="parent_id"),
    inverseJoinColumns=@JoinColumn(name="child_id")
)
@OrderColumn(name="child_order")
public List<Child> getChildren() {
    return children;
}

孩子:

@ManyToOne
public Parent getParent() {
    return parent;
}

这是我的问题:父表符合预期,但这里是子表和 parent_child 表:

孩子:

int8 id,
int8 parent_id <---

父子:

int8 parent_id, <---
int8 child_id,
int8 child_order

与 parent_id 重复 - 它在连接表和子表中指定,这意味着可以调用 parent.getChildren().get(0).getParent() 并最终得到与您不同的父级开始,这应该是不可能的(我希望在数据库级别强制执行)。

我能看到解决此问题的唯一方法是在子项中使用连接列,而根本不使用连接表。但我不喜欢这样,因为那时我必须将订单转移给孩子,而且休眠文档说应该避免使用 OneToMany 的 JoinColumn(但他们并没有真正说明原因)。

还有其他方法可以消除这种重复/可能的不一致吗? IE。通过使用连接表中的数据让孩子知道其父母的某种方式?

【问题讨论】:

    标签: java hibernate jpa persistence jpa-2.0


    【解决方案1】:

    如果可行,试试这个。注意 JoinColumn 的使用

       @OneToMany(cascade=CascadeType.ALL)
       @OrderColumn(name="child_order")
       public List<Child> getChildren() {
             return children;
       }
    

    孩子

       @ManyToOne
       @JoinColumn("parent_id")
       public Parent getParent() {
           return parent;
       }
    

    【讨论】:

      【解决方案2】:

      与 parent_id 重复 - 它在连接表和子表中指定,这意味着可以调用 parent.getChildren().get(0).getParent() 并最终得到与您不同的父级开始于

      当一个孩子只能有一个父母时,我不明白这怎么可能。对于给定的父子元组,应该有一个且只有一个记录 int 数据库,并且孩子永远不会存在于任何其他父子元组中。当然,父项将在 parent_child 表中重复,但永远不会重复子项。您是否在数据库表上指定了外键约束?在 getParent() 方法中使用 mappedBy 元素。

      【讨论】:

        【解决方案3】:

        我在Constraint violation in Hibernate unidirectional OneToMany mapping with JoinTable and OrderColumn when removing elements 中回答了类似的问题

        请看
        我认为您对关联表的约束是不好的,并且与 List 的原则不兼容。

        【讨论】:

          猜你喜欢
          • 2023-04-09
          • 1970-01-01
          • 2019-05-21
          • 1970-01-01
          • 2011-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-17
          相关资源
          最近更新 更多