如何迭代树数据?

时间:2016-01-27 08:51:05

标签: java hibernate spring-mvc

我有一个像enter image description here

这样的数据结构

当我使用

查询此数据库时
List<TextualReq> textualReqList = session.createQuery("from TextualReq where parent is null").list();

此处 TextualReq 对象

  @Id
       @GeneratedValue( generator = "increment" )
       @GenericGenerator( name = "increment", strategy = "increment" )
       @Column(name="ID")
       private int                    id;

       @ManyToOne
       @JoinColumn(name="parent")
       private TextualReq                parent;
       @OneToMany( mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER )
       @Column(name="children")
       private Set<TextualReq> children = new HashSet<TextualReq>();
       @Column(name="data")
       private String                  data;

我将在&#34; textualReqList&#34;中获得两条记录。我需要迭代并显示这些数据 enter image description here

2 个答案:

答案 0 :(得分:1)

我认为应该这样做!

public void displayData(){
    display(null);
}
public void display(TextualReq textualReq){
    List<TextualReq> textualReqList = null;

    String parentId = "is null"; 
    if(textualReq!=null){
        parentId = "= "+textualReq.Id;
        System.out.println(textualReq.data);
        System.out.print(" ");
    }
    textualReqList = session.createQuery("select * from TextualReq where parent "+parentId).list();
    if(textualReqList==null)
        return;
    for(int i=0;i<textualReqList.size();i++){
        display(textualReqList.get(i));
    }
}

只需调用函数 displayData()

答案 1 :(得分:0)

我建议在TextualReq类中添加toString()方法:

public String toString() {
    return toStringWithPrefix("");
}

private String toStringWithPrefix(String prefix) {
    StringBuilder childrenAsString = new StringBuilder();
    for (TextualReq child : children) {
        childrenAsString.append(child.toStringWithPrefix(prefix + '\t'));
    }
    return String.format("%s%s%n%s", prefix, data, childrenAsString);
}

然后你可以迭代textualReqList并打印每一个项目:

for (TextualReq req : textualReqList) {
    System.out.print(req);
}