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 column 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?