来自数据库的Primefaces树

时间:2012-06-25 12:48:34

标签: java tree primefaces

我有以下实体类:

@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 >();

我想将此表示为primefaces树,但我无法正确使用它。 primefaces网站中给出的示例包含具有预定义深度的静态节点,其中我需要具有未知深度的节点并从数据库填充。我在这里看过各种帖子,但对我来说没什么好看的。在这个post中,似乎作者提出了同样的问题,但答案与某个问题无关。任何解决方案都将不胜感激。

1 个答案:

答案 0 :(得分:8)

您必须创建一个递归函数来创建树。我就是这样做的:

@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;
     }

 }