Skip to content

Instantly share code, notes, and snippets.

@mvodep
Last active May 2, 2021 16:13
Show Gist options
  • Save mvodep/21c454cefa8f9078d02814c9eb04fdb7 to your computer and use it in GitHub Desktop.
Save mvodep/21c454cefa8f9078d02814c9eb04fdb7 to your computer and use it in GitHub Desktop.
@Entity
@Table(name = "nodes", schema = "playground", catalog = "postgres")
public class NodesEntity {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Basic
@Column(name = "node_name", nullable = false, length = 10)
private String nodeName;
@OneToMany(mappedBy = "fromNode", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<EdgesEntity> edges = new LinkedHashSet<>();
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNodeName() { return nodeName; }
public void setNodeName(String nodeName) { this.nodeName = nodeName; }
}
@Entity
@Table(name = "edges", schema = "playground", catalog = "postgres")
public class EdgesEntity {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "from_node_id", nullable = false)
private NodesEntity fromNode;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "to_node_id", nullable = false)
private NodesEntity toNode;
@Basic
@Column(name = "type", nullable = false, length = 20)
private String type;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public NodesEntity getFromNode() { return fromNode; }
public void setFromNode(NodesEntity fromNode) { this.fromNode = fromNode; }
public NodesEntity getToNode() { return toNode; }
public void setToNode(NodesEntity toNode) { this.toNode = toNode; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
NodesEntity nodeA = new NodesEntity();
nodeA.setNodeName("A");
NodesEntity nodeB = new NodesEntity();
nodeB.setNodeName("B");
EdgesEntity entityAToB = new EdgesEntity();
entityAToB.setFromNode(nodeA);
entityAToB.setToNode(nodeB);
entityAToB.setType("parent");
nodeA.edges.add(entityAToB);
EdgesEntity entityBToA = new EdgesEntity();
entityBToA.setFromNode(nodeB);
entityBToA.setToNode(nodeA);
entityBToA.setType("child");
nodeB.edges.add(entityBToA);
session.save(nodeA);
} finally {
session.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment