How to convert a tree stored in a database into a tree list (take Easyui as an example)

Source: Internet
Author: User

Many times, we will put a tree into the database, the current station needs to show a tree list, the tree read out and show, how this process is implemented?

This article is an example of a tree-shaped list that constructs a Easyui foreground frame, and the background frame is spring MVC+JPA.

First look at how the tree is stored in the database:


Tree structure at a glance, this is a tree representing the department.

Here is the entity class:

/** * Departmental User departments (where the department is a relatively abstract word) * Use prefix encoding, add three numbers per level, such as: Level 001, Level 001001, Level 001001001 * @author Administrator * */@Entitypu Blic class Department {   private String ID;          Department ID private String PID;         Parent idprivate String text;        Department name private list<department> children;   Used to store child nodes @idpublic String getId () {return ID;} public void SetId (String id) {this.id = ID;} Public String Getpid () {return PID;} public void Setpid (String pid) {this.pid = pid;} Public String GetText () {return text;} public void SetText (String text) {this.text = text;} @OneToManypublic list<department> GetChildren () {return children;} public void Setchildren (list<department> children) {This.children = children;}    }
Because the Easyui is used, for the tree to be displayed correctly, the property ID and text must be included.

The following is the control class, which is used to read the data in the database, to generate a list, the list will be returned to the foreground in JSON format data, the key needs to understand is gettree () and Buildtree () These two methods, through the recursive generation of this tree, The basic implementation principle is to traverse a layer of the tree, get the child nodes of each node (a list), and then use it as a property set in the parent node.

@Controller @requestmapping ("/department") public class Departmentcontroller {private static final String Departemntmanage = "module/jsp/system/departmentmanage.jsp"; @Resource (name= "Departmentserviceimpl") private Departmentservice departmentservice;/** * Get the Department admin page. * @return */@RequestMapping ("/getpage.do") public String Getusermanagepage () {return departemntmanage;} /** * Get Department Tree list */@RequestMapping (value = "/gettree.do", method = Requestmethod.post) @ResponseBody//This note indicates that the return value skips the View Processing section, Write directly to HTTP response body in public list<department> gettree () {list<department> root =  Departmentservice.findbyid ("0"); Gets the root node (the obtained value is stored in the list) Net.sf.json.JSONArray Jsonarray = Net.sf.json.JSONArray.fromObject (Buildtree (root));    System.out.println (Jsonarray.tostring ()); return buildtree (root);} Public list<department> buildtree (list<department> root) {for (int i=0;i<root.size (); i++) {list< department> children = departmentservice.findbypid (Root.get (i). GetId ()); Querying a node's child node (gets a list) buIldtree (children); Root.get (i). Setchildren (children);}    return root; }    }
Here are the methods of querying FindByID and Findbypid are based on the spring data JPA method, the following is the related class:

Public interface Departmentdao extends Repository<department, integer>{public     list<department> Findbypid (String pid);     Public list<department> FindByID (String ID);}

Public interface Departmentservice {public list<department> findbypid (String pid);    Public list<department> FindByID (String ID);}

@Service ("Departmentserviceimpl") public class Departmentserviceimpl implements departmentservice{@Autowiredprivate Departmentdao Departmentdao; @Overridepublic list<department> findbypid (String pid) {return Departmentdao.findbypid (PID);} @Overridepublic list<department> FindByID (String ID) {return Departmentdao.findbyid (ID);}}

The foreground call is as follows:

$ (function () {       $ (' #tt '). Tree ({        URL: ' department/gettree.do ',        loadfilter:function (data) {    if ( DATA.D) {                return DATA.D;            } else {                return data;}}       );      });
This is the background returned to the foreground with the following JSON-formatted data:

[{"Children": [{"Children": [{] Childre                    N ": []," id ":" 001001 "," pid ":" 001 "," Text ":" Department One "                        }, {"Children": [], "id": "001002",                "pid": "001", "Text": "Department Two"}], "id": "001", "pid": "0", "text": "One Branch"}, {"Child                        ren ": [{" Children ": []," id ":" 002001 ",                        "pid": "002", "text": "Department One"}, { "Children": [], "id": "002002", "pid": "002", "Tex               T ":" Department two "     }], "id": "002", "pid": "0", "text": "Two Branch"} , {"Children": [], "id": "003", "pid": "0", "text" : "Three Branch"}], "id": "0", "pid": "1", "text": "Head Office"}]

On the page as shown below:


Basically this is achieved, if you feel that the small writing can add Q to explore or reply below


How to convert a tree stored in a database into a tree list (take Easyui as an example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.