问题
I have the following entity class :
@Entity
@Table(name = "THE_TREE", catalog = "", schema = "dbo")
public class TheTree implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "NODE_NAME")
private String name;
@Column(name = "LEVEL")
private int level;
@OneToMany
@JoinColumn(name="PARENTID")
public List<TheTree > children = new LinkedList<TheTree >();
I would like to represent this into primefaces tree, but I cant get it right. The example given in primefaces website has static nodes with predefined depth, where I need nodes with unknown depth and to be filled from database. I have seen various posts here but nothing is clear to me. In this post it seems the author has asked the same question but the answer is not relative to the question somehow. Any solution would be appreciated.
回答1:
You have to create a recursive function to make the tree. This is how I would do it:
@ManagedBean
@ViewScoped
public class TreeMBean {
private TreeNode rootNode;
@PostConstruct
public void init() {
TheTree root = new TheTree(); // instead get root object from database
rootNode = newNodeWithChildren(root, null);
}
/**
* recursive function that returns a new node with its children
*/
public TreeNode newNodeWithChildren(TheTree ttParent, TreeNode parent){
TreeNode newNode= new DefaultTreeNode(ttParent, parent);
for (TheTree tt : ttParent.getChildren()){
TreeNode newNode2= newNodeWithChildren(tt, newNode);
}
return newNode;
}
public TreeNode getRootNode() {
return rootNode;
}
public void setRootNode(TreeNode node) {
rootNode = node;
}
}
来源:https://stackoverflow.com/questions/11189697/primefaces-tree-from-database