View Javadoc
1   package myorg.relex.many2many;
2   
3   import java.util.HashSet;
4   import java.util.Set;
5   import java.util.UUID;
6   
7   import javax.persistence.*;
8   
9   /**
10   * This class provides an example of a many-to-many, bi-directional relationship that just
11   * happens to be recursive. Both ends of the relationship reference an instance of this class. 
12   */
13  @Entity
14  @Table(name="RELATIONEX_NODE")
15  public class Node {
16  	@Id
17  	@Column(length=36, nullable=false)
18  	private String id;
19  	
20  	@ManyToMany(cascade={CascadeType.PERSIST}, fetch=FetchType.LAZY)
21  	@JoinTable(name="RELATIONEX_NODE_REL",
22  			joinColumns=@JoinColumn(name="PARENT_ID"),
23  			inverseJoinColumns=@JoinColumn(name="CHILD_ID"))
24  	private Set<Node> children;
25  	
26  	@ManyToMany(mappedBy="children", fetch=FetchType.EAGER)
27  	private Set<Node> parents;
28  	
29  	@Column(length=32, nullable=false)
30  	private String name;
31  	
32  	public Node() { id=UUID.randomUUID().toString(); }
33  	public Node(String name) {
34  		this();
35  		this.name = name;
36  	}
37  	public Node(Node parent, String name) {
38  		this();
39  		this.name = name;
40  		parent.getChildren().add(this);
41  		getParents().add(parent);
42  	}
43  
44  	public String getId() { return id; }
45  	public String getName() { return name; }
46  	public void setName(String name) {
47  		this.name = name;
48  	}
49  
50  	public Set<Node> getChildren() {
51  		if (children==null) {
52  			children = new HashSet<Node>();
53  		}
54  		return children;
55  	}
56  	
57  	public Set<Node> getParents() {
58  		if (parents == null) {
59  			parents = new HashSet<Node>();
60  		}
61  		return parents;
62  	}
63  	
64  	@Override
65  	public int hashCode() {
66  		return id==null?0:id.hashCode();
67  	}	
68  	@Override
69  	public boolean equals(Object obj) {
70  		try {
71  			if (this == obj) { return true; }
72  			Node rhs = (Node)obj;
73  			if (id==null && rhs.id != null) { return false; }
74  			return id.equals(rhs.id);
75  		} catch (Exception ex) { return false; }
76  	}
77  }