I believe that you will often encounter this kind of requirement. You can use the id/name of a staff member to obtain a list of all its employees (including non-subordinate employees, it may take a while to implement this function using java, but it would be so easy if you rely on databases to implement this function. Let's take a look at how Postgresql implements such a feature.
- With recursive r AS (SELECT * FROM t_account WHEREname =#{ accountName}
- UnionALL
- SELECT t_account. * FROM t_account, r WHERE t_account.parent = r. name
- )
- SELECT * FROM r ORDERBYname
This is not in the amount of code to reduce a lot of ah, see the postgresql official documentation http://www.postgresql.org/docs/8.4/static/queries-with.html
Next let's take a look at how Oracle performs recursive queries:
Traverse from ROOT to end:
Select * from t_account t start with t. parent is null connect by prior t. name = t. parent
Traverse from the end to the ROOT end: select * from t_account t start with t. name = '** 'connect by t. parent = t. name
For more information, see the oracle documentation.
See the java Implementation below:
- Publicclass JsonTreeGenerate <T extends AbstractTreeNode> {
- Private Logger logger = Logger. getLogger (JsonTreeGenerate. class );
- Private Lock lock = new ReentrantLock ();
- Private Set <T> set = new HashSet <T> ();
- Public Set <T> getAllChild (Set <T> sets, T node ){
- Lock. lock ();
- Try {
- If (set. size ()> 0 ){
- Set. clear ();
- }
- RecursionFn (sets, node );
- } Catch (Exception e ){
- Logger. error ("", e );
- } Finally {
- Lock. unlock ();
- }
- Return set;
- }
- Publicvoid recursionFn (Set <T> sets, T node ){
- Set. add (node );
- If (hasChild (sets, node )){
- List <T> hashSet = getChildList (sets, node );
- Iterator <T> it = hashSet. iterator ();
- While (it. hasNext ()){
- T n = (T) it. next ();
- If (null = node. getChildren ()){
- Node. setChildren (new ArrayList <AbstractTreeNode> ());
- }
- Node. getChildren (). add (n );
- RecursionFn (sets, n );
- }
- // RecursionFn (accountSet, node );
- }
- }
- Public List <T> getChildList (Set <T> list, T t ){
- List <T> nodeList = new ArrayList <T> ();
- Iterator <T> it = list. iterator ();
- While (it. hasNext ()){
- T accounts = it. next ();
- If (accounts. getParent () = t. getId ()){
- NodeList. add (accounts );
- // T. getChildren (). add (accounts );
- }
- }
- Return nodeList;
- }
- Publicboolean hasChild (Set <T> list, T node ){
- List <T> l = getChildList (list, node );
- If (null! = L & l. size ()> 0 ){
- Returntrue;
- }
- Returnfalse;
- }
- }
This comparison shows the conciseness of the former to solve this problem.