I have a tree like data structure with some sort of composite pattern. With an abstract class Element, there is a CompositeElement and a SingleElement. It looks like this:
@Entity
@DiscriminatorValue("Composite")
public class CompositeElement extends Element {
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name="Sub_Elements")
@MapKeyColumn(name="xxx")
protected Map<Integer, Element> subs;
...
}
Until now, the relation was unidirectional. It worked well. But now a use case popped up where I need to navigate from a sub element to the parent element. So what I'd love to do is this:
@Entity
@Inheritance
@DiscriminatorColumn("s_discriminator")
public class Element {
@ManyToOne(mappedBy="subs", fetch=FetchType.LAZY)
protected CompositeElement parent;
...
}
But the @ManyToOne Annotation doesn't allow a "mappedBy" attribute.
From a domain view, the parent owns the children objects in the data structure. Not the other way around. This is also emphasised by the eager fetch and the cascade rule.
If the ownership of the relationship was on the child side, then child.setParent(p) wouldn't really work because here I'm missing the key for the map.
Is there any way to keep the ownership of the relation on the side of the parent but still make it bidirectional?