Self-Referencing One-to-Many Bidirectional Relationship


@Entity
public class Person {


    /**
     * Adopts given <code>child</code>.
     *
     * @param child the child to be adopted.
     */
    public void adopt(final Person child) {

        if (child == null) {
            throw new NullPointerException("null child");
        }

        if (child.parent != null) {
            // how cruel
            child.parent.getChildren().remove(child);
            child.parent = null;
        }

        child.parent = this;
        getChildren().add(child);
    }


    /**
     * Returns the children of this person.
     *
     * @return the children of this person
     */
    public List<Person> getChildren() {

        if (children == null) {
            children = new ArrayList<Person>();
        }

        return children;
    }


    /**
     * id.
     */
    @Id
    @XmlAttribute
    @XmlID
    @XmlJavaTypeAdapter(XmlIDAdapter.class) // MOXy doesn't need this
    private Long id;


    @Basic
    @Column
    private String name;


    @Basic
    @Column
    private int age;


    /**
     * parent.
     */
    @JoinColumn
    @ManyToOne
    @XmlAttribute(name = "parentId")
    @XmlIDREF
    private Person parent;


    /**
     * children.
     */
    @JoinColumn
    @OneToMany(mappedBy = "parent")
    @XmlAttribute(name = "childIds")
    @XmlIDREF
    @XmlList
    private List<Person> children;


}
public class XmlIDAdapter extends XmlAdapter<String, Long> {


    @Override
    public String marshal(final Long bound) throws Exception {

        if (bound == null) {
            return null;
        }

        return DatatypeConverter.printLong(bound);
    }


    @Override
    public Long unmarshal(final String value) throws Exception {

        if (value == null) {
            return null;
        }

        return DatatypeConverter.parseLong(value);
    }


}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s