Self referencing symmetrical Hibernate Map Table using @ManyToMany

Posted by sammichy on Stack Overflow See other posts from Stack Overflow or by sammichy
Published on 2010-03-23T15:44:19Z Indexed on 2010/03/23 19:53 UTC
Read the original article Hit count: 654

Filed under:
|
|

I have the following class

public class ElementBean {
    private String link;
    private Set<ElementBean> connections;
}

I need to create a map table where elements are mapped to each other in a many-to-many symmetrical relationship.

@ManyToMany(targetEntity=ElementBean.class)
@JoinTable(
    name="element_elements",
    joinColumns=@JoinColumn(name="FROM_ELEMENT_ID", nullable=false),
    inverseJoinColumns=@JoinColumn(name="TO_ELEMENT_ID", nullable=false)
)
public Set<ElementBean> getConnections() {
    return connections;
}

I have the following requirements

When element A is added as a connection to Element B, then element B should become a connection of Element A. So A.getConnections() should return B and B.getConnections() should return A. I do not want to explicitly create 2 records one for mapping A to B and another for B to A.

Is this possible?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about manytomany