Skip to content

Instantly share code, notes, and snippets.

@michail-nikolaev
Created October 5, 2012 16:55
Show Gist options
  • Save michail-nikolaev/3840973 to your computer and use it in GitHub Desktop.
Save michail-nikolaev/3840973 to your computer and use it in GitHub Desktop.
JPA - Tree structure with automatic order and tested operations for it
@Entity
public class TreeCategory extends IdentifiableEntity {
....
@ManyToOne(optional = true)
@JoinColumn(name = "parent_id", referencedColumnName = "id")
public TreeCategory getParent() {
return parent;
}
public void setParent(TreeCategory parent) {
this.parent = parent;
}
...
@OrderColumn(name = "position")
@OneToMany(
cascade = {CascadeType.ALL},
orphanRemoval = true
)
@JoinColumn(name = "parent_id")
public List<TreeCategory> getChildren() {
return children;
}
public void setChildren(List<TreeCategory> children) {
this.children = children;
}
...
// Operations:
public void move(TreeNode node, TreeNode newParent, TreeNode oldParent) {
TreeCategory TreeCategory = dao.getById(Long.parseLong(node.getId()));
TreeCategory newParentCategory = dao.getById(Long.parseLong(newParent.getId()));
TreeCategory oldParentCategory = dao.getById(Long.parseLong(oldParent.getId()));
TreeCategory.setParent(newParentCategory);
newParentCategory.getChildren().add(TreeCategory);
oldParentCategory.getChildren().remove(TreeCategory);
dao.update(oldParentCategory);
dao.update(newParentCategory);
dao.update(TreeCategory);
}
public void delete(TreeCategory entity) {
entity.getParent().getChildren().remove(entity);
update(entity.getParent());
}
public TreeCategory addChild(TreeCategory TreeCategory, String name, TreeCategory.Type type) {
TreeCategory child = new TreeCategory();
child.setName(name);
child.setType(type);
child.setParent(TreeCategory);
TreeCategory.getChildren().add(child);
TreeCategory = update(TreeCategory);
return TreeCategory.getChildren().get(TreeCategory.getChildren().size() - 1);
}
public void toIndex(String id, Long index) {
TreeCategory treeCategory = dao.getById(Long.parseLong(id));
TreeCategory parent = treeCategory.getParent();
if (parent != null) {
if (parent.getChildren().indexOf(treeCategory ) != index) {
parent.getChildren().remove(treeCategory );
parent.getChildren().add(index.intValue(), treeCategory );
dao.update(parent);
}
}
}
// tested on Hibernate 4.1.4.Final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment