开发者

Remove duplication in OneToMany/ManyToOne bidirectional relationship using a JoinTable (with an OrderColumn)

I have a OneToMany/ManyToOne bidirectional relationship using a join table. The children are in a List and are ordered.

Here's the setup:

Parent:

@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;
}

Child:

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

Here's my issue: The parent table is as expected, but here are the child and parent_child tables:

child:

int8 id,
int8 parent_id <---

parent_child:

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

There's duplication with the parent_id - it's specified in the join table and in the child table which means that it's possible to call parent.getChildren().get(0).getParent() and end up with a different parent than you started with, which should be impossible (and I'd like that to be enforced at the database level).

The only way I can see to fix this is to use a join c开发者_Python百科olumn in the child, and not use a join table at all. But I don't like that because then I have to move the order to the child, plus the hibernate docs say that a JoinColumn with OneToMany should be avoided (but they don't really say why).

Is there any other way of getting rid of this duplication/possible inconsistency? I.e. some way of having the child know its parent by using the data from the join table?


Try this if it works. Note the use of JoinColumn

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

child

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


There's duplication with the parent_id - it's specified in the join table and in the child table which means that it's possible to call parent.getChildren().get(0).getParent() and end up with a different parent than you started with

I don't understand how can that be possible, when a child can have only one parent. There should be one and only one record int database for a given parent-child tuple and the child will never exists in any other tuple of parent-child. Ofcourse the parent will be repeated in the parent_child table but never will a child be repeated. Have you specified the foreign key constraints on the database tables? Use the mappedBy element on the getParent() method.


I answer to a similar question in Constraint violation in Hibernate unidirectional OneToMany mapping with JoinTable and OrderColumn when removing elements

Please have a look
I think your constraints on your association table is bad and incompatible with the principle of a List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜