java 数据库中的素面树
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11189697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Primefaces tree from database
提问by fareed
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 primefaceswebsite 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 postit seems the author has asked the same question but the answer is not relative to the question somehow. Any solution would be appreciated.
我想将其表示为素数树,但我无法做到。primefaces网站中给出的示例具有预定义深度的静态节点,其中我需要未知深度的节点并从数据库中填充。我在这里看到了各种帖子,但对我来说什么都不清楚。在这篇文章中,作者似乎问了同样的问题,但答案与问题无关。任何解决方案将不胜感激。
回答by damian
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;
}
}