Skip to content

Instantly share code, notes, and snippets.

@khannedy
Created October 15, 2011 04:55
Show Gist options
  • Select an option

  • Save khannedy/1289070 to your computer and use it in GitHub Desktop.

Select an option

Save khannedy/1289070 to your computer and use it in GitHub Desktop.
Menampilkan Data Bertingkat ke JTree Menggunakan Hibernate
@Entity
@Table(name = "stripbandunk_category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "parent")
private Category parent;
@OneToMany(mappedBy = "parent")
private List<Category> categories = new ArrayList<Category>(0);
// getter dan setter
}
public class CategoryTreeModel implements TreeModel {
private Object root;
private List<Category> categories;
public CategoryTreeModel(Object root, List<Category> categories) {
this.root = root;
this.categories = categories;
}
public Object getRoot() {
return root;
}
public Object getChild(Object parent, int index) {
if (parent == root) {
return categories.get(index);
} else if (parent instanceof Category) {
Category category = (Category) parent;
return category.getCategories().get(index);
} else {
return null;
}
}
public int getChildCount(Object parent) {
if (parent == root) {
return categories.size();
} else if (parent instanceof Category) {
Category category = (Category) parent;
return category.getCategories().size();
} else {
return 0;
}
}
public boolean isLeaf(Object node) {
if (node instanceof Category) {
Category category = (Category) node;
return category.getCategories().isEmpty();
} else {
return false;
}
}
public void valueForPathChanged(TreePath path, Object newValue) {
// do nothing
}
public int getIndexOfChild(Object parent, Object child) {
if (parent instanceof Category) {
Category parentcategory = (Category) parent;
return parentcategory.getCategories().indexOf(child);
} else if (parent == root) {
return categories.indexOf(child);
} else {
return 0;
}
}
public void addTreeModelListener(TreeModelListener l) {
// do nothing
}
public void removeTreeModelListener(TreeModelListener l) {
// do nothing
}
}
Session session = HibernateHelper.getSessionFactory().openSession();
@SuppressWarnings("unchecked")
List<Category> list = session.createQuery("from Category a where a.parent is null").list();
CategoryTreeModel treeModel = new CategoryTreeModel("Root", list);
jTreeCategory.setModel(treeModel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment