简体   繁体   中英

Dynamic Tree Creation in Java

I am using Spring-hibernate Framework and Oracle database. Now there is a table named project. each record has got an unique id,name and a parent_id column. Say the table has got these following records...

ID NAME PARENT_ID
1  A     NULL
2  B     1
3  C     NULL
4  D     3
5  E     3

now i have create a tree view where these records will be displayed in according to their Parent-Child relationship. Like This..

1---P
   ch---2
3---P
   ch--4
   ch--5

Now can anyone help me how to create the tree dynamically fetching records from the database dynamically. And what will be the Data Access Object(DAO) and the Implementation of the DAO..

any help or suggestion will be very helpful.

First select only PARENT_ID. Then for select everything where ID is IN the previous array of results ( http://www.w3schools.com/sql/sql_in.asp ).

  • From this you can then create parent in the tree and then lazy load children on expand.
  • Or you can populate tree with children immidiately. You just select all where PARENT_ID is NOT NULL and attach them to appropriate parent (by PARENT_ID).

I'm not sure what DAO has to do with it. But in case you just want some abstraction you can use DAO pattern.

DAO could have methods like: getAllParents, getChildrenForParentId, getAllChildren, ...

Just made self table reference in POM (.java class) with List type one to many annotation.

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "PARENT_ID",nullable=true)
@OrderBy(clause = "NAME")
@ForeignKey(name = "fk_child_project")     
private List<Project> projects= new ArrayList<Project>(); 

What you need is a Oracle Hierarchical query . Since you are using Oracle DB, you are in luck.

But the only way this can done thru Hibernate is by using a native query and mapping the results back to Objects.

Too many questions, I'll try to steer you in the right direction -- this might not drop you to your destination.

  • Create your Entities , See the docs
  • You may not need a DAO, just create a business class to query the database. (Hint: use EntityManager in case you are using Hibernate's JPA implementation), See the docs
  • Then display it as a tree in your browser, assuming you are working on a webapp

Note: You can come again and ask specific questions regarding how, as a separate question.

Related thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM