Create a tree from a resultset

Hi,
I need to create a tree structure from a resultset and show them into my JSP. Here is my table sql (grup).
CREATE TABLE GRUP (
ID_GRUP int(11) NOT NULL default '0',
ID_GRUP_PARENT int(11) NOT NULL default '0',
ORDER_BY int(11) NOT NULL default '1',
DESCRP varchar(100) default NULL,
PRIMARY KEY ('ID_GRUP'),
)What I really need is a recursive method to search for all the children of each row and build a tree heirarchy. e.g. the data may look like
ID_GRUP   ID_GRUP_PARENT      ORDER_BY    DESCRP
1               0                 1        It itself is the parent
2               1                 1        It's Parent is ID_GRUP=1
3               0                 2        It itself is the parent
4               2                 1        It's parent is ID_GRUP=2
5               1                 2        It's Parent is ID_GRUP=1
6               4                 1        It's Parent is ID_GRUP=4
7               2                 2        It's parent is ID_GRUP=2
8               2                 3        It's parent is ID_GRUP=2So looking at the top data my final tree structure should look like
1
  2
    4
      6
    7
    8
  5
3and so on. ORDER_BY show the order in which each element should display in the heirarchy. I am really struggling to find a way on how to have the heirarchy built and really need some help.
Thanks
Here is the SQL i have to het the data
SELECT ID_GRUP, ID_GRUP_PARENT, DESCRP FROM GRUP ORDER BY ORDER_BY.

First of all, you can't make a (single) tree out of that, because apparently you have two roots.
Anyway, one you fix the requirements, you can do this by defining a tree node type (of course), a reference to the root node, and then a temporary data structure to let you go directly to identified nodes without having to traverse the tree from the root (and thus having to know all the paths to the descendant elements). For example, in Java, a good temp data structure might be a java.util.Map<Integer, YourTreeNode>, where you'll use ID_GRUP values for the keys.

Similar Messages

  • How to create dynamic tree from db resultset?

    i have a db and sql that includes item_id, parent_id, level, description for all hierarchy.
    i want to show this resultset on the page as a adf tree component. How to convert from db resultset to adf tree?
    that is my sql -&gt;SELECT LEVEL, display_title, item_id, parent_id, sac_Hierarchy.Branch(level,description) branch FROM XXXTABLE CONNECT BY job_code = 'ABCD' AND PRIOR item_id = parent_id START WITH job_code = 'ABCD' AND parent_id IS NULL;
    What can i do on backing java or what can i do on jsp page?
    Help Please.
    thanks
    Edited by: Mehmet Özkan on Aug 30, 2008 12:19 PM

    mehmet,
    Have you seen [url http://technology.amis.nl/blog/?p=2116]this?
    John

  • Creating dynamic lists from db resultset

    Hello, Not sure if this is the right forum but I am hoping someone can point me in the right direction.
    I have tried to set up a popup menu with JRadioButtonMenuItem (s) or a JTable from the resultset and then select from the list as input to the next db query (OracleSE db).
    What I cannot do is retrieve the value.
    With "JRadio" I cannot use 'this' on the button in the listener.
    With JTable I cannot extend the object.
    If there are examples then I would be grateful for leads, none of what I have seen goes this deep.
    Thanks,
    Ralph.
    Edited by: user548412 on Feb 21, 2012 6:05 PM

    It would be helpful if you posted your code inside the tags so it became readable. Please do that next time.
    And also: what's your question about that code? I don't see any JDBC code in there; did you have a JDBC question of some kind? If so, what is it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Create a tree from XML

    hi. I have created a simple XML file which contains a hierarchical structure of strings.
    Also, I have created a SAXParser to read from the xml.
    But I don't know how to put this structure in a JTree.I don't want to show the tree on screen. I want to be able to access certain nodes at different times.
    Any help?

    I've created the SAXParser and as you can see I've read the XML file. I need to write some code in the characters method to add the relecvant strings to the tree. I'm quite new at this...
    public class Echo extends DefaultHandler
    public static void main(String args[])
    DefaultHandler handler=new Echo();
    SAXParserFactory factory=SAXParserFactory.newInstance();
    try
    SAXParser saxParser=factory.newSAXParser();
    saxParser.parse(new File("meniu.xml"),handler);
    }catch(Throwable t)
    t.printStackTrace();
    System.exit(0);
    public void startDocument()
    throws SAXException
    public void endDocument()
    throws SAXException
    public void startElement(String namespaceURI,
    String sName,
    String qName,
    Attributes attrs)
    throws SAXException
    String eName=sName;
    if("".equals(eName)) eName=qName;
    public void endElement(String namespaceURI,
    String sName,
    String qName)
    throws SAXException
    public void characters(char[] buf,int offset, int len)
    throws SAXException
    String s=new String(buf,offset,len);
    if(!s.trim().equals("")) {

  • How to create af:tree from single database Table

    Hi,
    i want to create tree Like this: and also we can add node anywhere.
    Parent01
    ----|parent01-child01
    --------|parent01-child01-child01
    --------|parent01-child01-child02
    -------------|parent01-child01-child02-child01
    Parent02
    ----|parent02-child01
    ----|parent02-child02
    --------|parent02-child02-child01
    and for this i have created Table like this :
    Table name Treetable
    NODEID     NUMBER(38,0) --> Primary Key
    NODENAME     VARCHAR2(50 BYTE) --> This is the name will display as a node
    DESCRIPTION     VARCHAR2(255 BYTE)     
    ROOTIND     CHAR(1 BYTE) --> to decide root node
    SEQUENCENO     NUMBER(38,0)     --> order to display node
    PARENTKEY     NUMBER(38,0) -->FK (refering to NODEID(PK) of this table)
    But when i am creating tree, its showing root node for each row in the table. but my requirement is: The Row marked as ROOTIND='Y' , show that row only as Root (Example in above tree:Parent01 & Parent02 )
    any help highly appreciated :)
    Thanks
    Pratap Rudra
    Edited by: 995114 on Apr 30, 2013 2:50 PM

    Hi,
    check this http://www.oracle.com/technetwork/developer-tools/adf/learnmore/32-tree-table-from-single-vo-169174.pdf
    Frank

  • Looking for code creating binary tree from expression(prefix)!

    I wanna use expression to generate binary expression tree. For example:
    I have expression in string: 1+2*3;
    then generate a tree like:
    +
    1 *
    2 3
    does some body have example code?

    sniff sniff I thought we were having lasagna? Smells like homework!

  • Create Tree from Preordered data

    Here is a quick summary of what I'm trying to do:
    I have a file with formatted like this
    Does it have legs?
    Dog
    Fish
    and the resulting tree for it should look like this
         Does it have legs?
         Dog        Fishand I'm trying to write a function that takes in a Scanner object that should already be tied to the data file and create a tree from this data that is already listed in Preorder fashion. I know tha recurison is probably the best way to go about this but everything that I have written hasn't worked. Also, I cant really figure out a way to use recursion when the function is taking in a Scanner I dont know how it would work.
    Any help would be greatly appreciated.
    Here is what I have now:
         public BinaryTree<String> readTree(Scanner data)
              BinaryTree<String> temp = new BinaryTree<String>();
              temp.attachLeft(data.next());
              temp.attachRight(data.next());
              return temp;
         }I know this function wont go through the whoel file, but I've tried many loops but I cant figure out how to get it to work so I'm convinced that I need to figure out how to make it recursive
    (yes I know that everything that can be done through recursion can be done with a loop)

    @OP:
    Here's how you could do it:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.Stack;
    class Main {  
        public static void main(String[] args) throws FileNotFoundException {
            Scanner file = new Scanner(new File("data.txt"));
            BinTree tree = new BinTree(file);
            System.out.println(tree);
    class BinTree  {
        private BinNode root;
        public BinTree(Scanner file) {
            // create the root (first line in the file)
            root = new BinNode(file.nextLine());
            // create a stack
            Stack<BinNode> stack = new Stack<BinNode>();
            // push the root on the stack: we need it to add nodes to the left and right of it
            stack.push(root);
            // call the insert method to build the tree
            insert(stack, file);
        private void insert(Stack<BinNode> stack, Scanner file) {
            IF 'file' has no more lines left
                stop this method
            END IF
            BinNode 'next' <- the next line in 'file'
            IF the left node of the last node on the 'stack' equals null
                the left child of last node of the stack <- 'next' (but leave the stack in tact)
            ESLE
                the right child of last node of the stack <- 'next' (remove the last node of the stack)
            END IF
            IF 'next' is a question
                push 'next' on the stack
            END IF
            recursively call the insert(...) method here
    class BinNode {
        String data;
        BinNode right, left;
        public BinNode(String data) { this.data = data; }
        public String toString() { return this.data; }
    }

  • How to create dynamic tree based on BAPI

    Hi
    I am able to create dynamic tree based on flat file structure example given in SDN . But how to create the tree from BAPI directly.Also when I will be clicking on any leaf node of the tree some data related to the node will be passed to another view.
    Regards
    Ananda

    What i'm trying to do is create an organizational structure.
    Global>Region>Plant-->Corporation
    The output from the RFC is a structure containing every possible combination for orgazational hierarchy. Basically a flat table with record for every possible combinaton of Region-Plant-Corporation. This data needs to be bound to a tree structure so that we can call BW queries based on that level. For example: Give me aged inventory for the SAP corporation within the plant Berlin that is located in the Europe region.
    Now that you understand the business reason will the nodes that represent Region and Plant and corporation be non-singleton nodes or recursive? I was thinking a hierarchy of non-singleton nodes.
    I can bind these nodes to the Region - Plant - Corporation elements returned from in the flat table structure. I will probably get duplicates as a specific Region will be listed multiple times for every possible combination of the data beneath it. I'm not so concerned about that right now as I want to make sure I understand how in Web Dynpro to bind the data to the tree.
    Hopefully this makes some sense. Can you elaborate on how this may be constructed in context of the view?
    Would i create a model node for region (0..n), model node for plant (0..n), and a model node for Corporation (0..n)?
    Or does this sound totally incorrect?
    julian
    We have 3 regions over 50 plants and probably around 500 corporations.

  • Creating Family Tree

    needed help creating family tree from 8000/9000 names, names are in different text box individually Any suggestions which can save my time

    Sure, you could do it with text boxes, pictures & lines, but I think it would be so much easier to use a dedicated genealogy program. The best known for the Mac is Reunion, but it may be more than you're willing to spend. Try a search on MacUpdate or VersionTracker for genealogy for shareware choices. I know there are a couple - Family 1.0 & Family Tree come to mind.

  • Need help Take out the null values from the ResultSet and Create a XML file

    hi,
    I wrote something which connects to Database and gets the ResultSet. From that ResultSet I am creating
    a XML file. IN my program these are the main two classes Frame1 and ResultSetToXML. ResultSetToXML which
    takes ResultSet & Boolean value in its constructor. I am passing the ResultSet and Boolean value
    from Frame1 class. I am passing the boolean value to get the null values from the ResultSet and then add those
    null values to XML File. When i run the program it works alright and adds the null and not null values to
    the file. But when i pass the boolean value to take out the null values it would not take it out and adds
    the null and not null values.
    Please look at the code i am posing. I am showing step by step where its not adding the null values.
    Any help is always appreciated.
    Thanks in advance.
    ============================================================================
    Frame1 Class
    ============
    public class Frame1 extends JFrame{
    private JPanel contentPane;
    private XQuery xQuery1 = new XQuery();
    private XYLayout xYLayout1 = new XYLayout();
    public Document doc;
    private JButton jButton2 = new JButton();
    private Connection con;
    private Statement stmt;
    private ResultSetToXML rstx;
    //Construct the frame
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    xQuery1.setSql("");
    xQuery1.setUrl("jdbc:odbc:SCANODBC");
    xQuery1.setUserName("SYSDBA");
    xQuery1.setPassword("masterkey");
    xQuery1.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
    contentPane.setLayout(xYLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Frame Title");
    xQuery1.setSql("Select * from Pinfo where pid=2 or pid=4");
    jButton2.setText("Get XML from DB");
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(java.lang.ClassNotFoundException ex) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(ex.getMessage());
    try {
    con = DriverManager.getConnection("jdbc:odbc:SCANODBC","SYSDBA", "masterkey");
    stmt = con.createStatement();
    catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton2_actionPerformed(e);
    contentPane.add(jButton2, new XYConstraints(126, 113, -1, -1));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_actionPerformed(ActionEvent e) {
    try{
    OutputStream out;
    XMLOutputter outputter;
    Element root;
    org.jdom.Document doc;
    root = new Element("PINFO");
    String query = "SELECT * FROM PINFO WHERE PID=2 OR PID=4";
    ResultSet rs = stmt.executeQuery(query);
    /*===========This is where i am passing the ResultSet and boolean=======
    ===========value to either add the null or not null values in the file======*/
    rstx = new ResultSetToXML(rs,true);
    } //end of try
    catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    ======================================================================================
    ResultSetToXML class
    ====================
    public class ResultSetToXML {
    private OutputStream out;
    private Element root;
    private XMLOutputter outputter;
    private Document doc;
    // Constructor
    public ResultSetToXML(ResultSet rs, boolean checkifnull){
    try{
    String tagname="";
    String tagvalue="";
    root = new Element("pinfo");
    while (rs.next()){
    Element users = new Element("Record");
    for(int i=1;i<=rs.getMetaData().getColumnCount(); ++i){
    tagname= rs.getMetaData().getColumnName(i);
    tagvalue=rs.getString(i);
    System.out.println(tagname);
    System.out.println(tagvalue);
    /*============if the boolean value is false it adds the null and not
    null value to the file =====================*/
    /*============else it checks if the value is null or the length is
    less than 0 and does the else clause in the if(checkifnull)===*/
    if(checkifnull){ 
    if((tagvalue == null) || tagvalue.length() < 0 ){
    users.addContent((new Element(tagname).setText(tagvalue)));
    else{
    users.addContent((new Element(tagname).setText(tagvalue)));
    else{
    users.addContent((new Element(tagname).setText(tagvalue)));
    root.addContent(users);
    out=new FileOutputStream("c:/XMLFile.xml");
    doc = new Document(root);
    outputter = new XMLOutputter();
    outputter.output(doc,out);
    catch(IOException ioe){
    System.out.println(ioe);
    catch(SQLException sqle){

    Can someone please help me with this problem
    Thanks.

  • Heap space error while creating XML document from Resultset

    I am getting Heap space error while creating XML document from Resultset.
    It was working fine from small result set object but when the size of resultset was more than 25,000, heap space error
    I am already using -Xms32m -Xmx1024m
    Is there a way to directly write to xml file from resultset instead of creating the whole document first and then writing it to file? Code examples please?
    here is my code:
    stmt = conn.prepareStatement(sql);
    result = stmt.executeQuery();
    result.setFetchSize(999);
    Document doc = JDBCUtil.toDocument(result, Application.BANK_ID, interfaceType, Application.VERSION);
    JDBCUtil.write(doc, fileName);
    public static Document toDocument(ResultSet rs, String bankId, String interfaceFileType, String version)
        throws ParserConfigurationException, SQLException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            Element results = doc.createElement("sims");
            results.setAttribute("bank", bankId);
            results.setAttribute("record_type", "HEADER");
            results.setAttribute("file_type", interfaceFileType);
            results.setAttribute("version", version);
            doc.appendChild(results);
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            String columnName="";
            Object value;
            while (rs.next()) {
                Element row = doc.createElement("rec");
                results.appendChild(row);
                for (int i = 1; i <= colCount; i++) {
                    columnName = rsmd.getColumnLabel(i);
                    value = rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    if(value != null)
                        node.appendChild(doc.createTextNode(value.toString()));
                    else
                        node.appendChild(doc.createTextNode(""));
                    row.appendChild(node);
            return doc;
    public static void write(Document document, String filename) {
            //long start = System.currentTimeMillis();
            // lets write to a file
            OutputFormat format = new OutputFormat(document); // Serialize DOM
            format.setIndent(2);
            format.setLineSeparator(System.getProperty("line.separator"));
            format.setLineWidth(80);
            try {
                FileWriter writer = new FileWriter(filename);
                BufferedWriter buf = new BufferedWriter(writer);
                XMLSerializer FileSerial = new XMLSerializer(writer, format);
                FileSerial.asDOMSerializer(); // As a DOM Serializer
                FileSerial.serialize(document);
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            //long end = System.currentTimeMillis();
            //System.err.println("W3C File write time :" + (end - start) + "  " + filename);
        }

    you can increase your heap size..... try setting this as your environment variable.....
    variable: JAVA_OPTS
    value: -Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m

  • JAXB: Creating Java content tree from scratch - examples?

    I'm trying to create XML output by building the content tree from scratch (using a the DDI schema which is fairly complex). I don't have any existing XML instances. Sample application 3 in Sun's JAXB tutorial doesn't give enough info about how to relate the nodes to create the heirarchy. I can create the root node and set it's attributes OK, but then the practical info runs out.
    Can anyone point me at some good practical examples? (i.e. not those of the "How to play the quitar: Put your fingers on the frets and move your other hand around" genre).
    Thanks in advance.

    I don't have examples, but the main thing to remember is that you should use the ObjectFactory to create all of the objects in your tree. That's important.
    You must use the element object class for the root node, but you can use type object classes for all the data contained (you can use element object classes for all the nodes, if that's easier).
    Use the accessor methods to load the data into the objects you create.
    One tip that almost everyone runs into - JAXB only provides a getter for lists - use the getter to get the list, then use .add() methods to add the objects to that list.

  • Creating a Java content tree from scratch and then marshal it to XML data

    Hi,
    After binding a schema using JAXB binding, I wrote a class to create a Java content tree from scratch and then marshal it to create an XML document. To see if the resulting xml document is correct, I opened it in XMLSpy and tried to validate it against the original schema.... I got the following error:
    "Unable to locate a reference to a supported schema kind (DTD, DCD, W3C Schema, XML-Data, Biz Talk) within this document instance"
    Then I realized that the generated xml document didnot contain the following for the root element:
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xsi:schemaLocation="....."
    i.e, the XML Schema Instance namespace and the schema location.
    How do I get these attributes incorporated into the XML document generated during the marshal process.
    Thanks.

    How do I get these attributes incorporated into the XML document generated during the marshal process.
    Add xmlns:xsi and xsi:schemaLocation attributes to the root element in the schema.
    <xsd:attribute name="xmlns:xsi"  fixed="http://www.w3.org/2001/XMLSchema-instance"/>

  • Create a Tree Node Structure from XML

    Hi
    We have a requirement where we have an XML file we want to create the Tree Node structure from the XML can anyone help out on this
    We are referring to the following blog but in that it is coming from KM content and we require the tree structure to form from a XML file
    http://wiki.sdn.sap.com/wiki/display/Snippets/SmartNavigationTreeforKM+Folders
    Can anyone help me
    Regards
    JM

    Hi,
    Could you elaborate a litle more exacly what you need to do?
    I found the link http://help.sap.com/saphelp_470/helpdata/en/86/8280db12d511d5991b00508b6b8b11/content.htm that maybe assist you.
    Please remember to evaluate the replays, this incentive the SDN to keep growing,
    regards,
    Fabio

  • Creating tree from HTTPService

    Hi, I'm new under flex builder and I have a simple (?)
    problem :
    I would like to generate a tree from a XML file generate by
    PHP. I can display items (source) in tree but not subitems
    (playlist)...
    Here my XML file generated by PHP :
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <sourcelist>
    <source id="3" nom="WarholinDaMix">
    <playlist id="0" nom="Tous les
    fichiers"></playlist>
    </source>
    <source id="2" nom="YoyesGirl">
    <playlist id="0" nom="Tous les
    fichiers"></playlist>
    <playlist id="2" nom="Yo la liste
    Girly"></playlist>
    </source>
    <source id="1" nom="Yoyesman">
    <playlist id="0" nom="Tous les
    fichiers"></playlist>
    <playlist id="1" nom="Yo ma liste 1"></playlist>
    <playlist id="3" nom="Yo ma liste 2"></playlist>
    </source>
    </sourcelist>
    Here the code I use :
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" creationComplete="GetSource.send(null);">
    <mx:HTTPService id="GetSource" url="
    http://127.0.0.1/SchmittTunes/bin/music.php?gettype=source"
    useProxy="false"/>
    <mx:Panel layout="absolute" left="10" right="10">
    <mx:Tree labelField="nom"
    dataProvider="{GetSource.lastResult.sourcelist.source}"
    width="100%" x="0" height="100%" y="0"
    showRoot="false"></mx:Tree>
    </mx:Panel>
    </mx:Application>
    How I said, I have 3 items displaying the 'source' on my
    tree, but I can't expand them. There is no arrow on the left side.
    So subitems like 'playlist' are not display.
    Does anyone know why or have an idea ?
    Thanks for your help
    Mika

    Thanks ! it's working with resultFormat="e4x" tag in my
    HTTPService, but with some adaptations :
    I change the following :
    <mx:Tree labelField="nom"
    dataProvider="{GetSource.lastResult.sourcelist.source}"
    width="100%" x="0" height="100%" y="0"
    showRoot="false"></mx:Tree>
    By :
    <mx:Tree labelField="@nom"
    dataProvider="{GetSource.lastResult}" width="100%" x="0"
    height="100%" y="0" showRoot="false"></mx:Tree>
    Changes are about labelfield and dataprovider.
    Thanks for your help !

Maybe you are looking for

  • Can I lock access to vi's using embedded but inactive copies of those vi's?

    The aim is to avoid race conditions between different vi's. A representative example is this: Will this vi reserve the vi's in the non-executing case structure? In reality the true case (shown above) will never be able to run, because the case is alw

  • Nokia E65 and iSync

    Hi all Until a few days ago everything went fine using a third party plugin. After executing the Security Update 2008-001 iSync didn't want to sync with my E65 any longer. I tried the original Nokia and several other plugins, but nothing worked. Is t

  • GIF to JPG problem - Orange tint

    I have tried numerous attempts to reliably create a JPG from a GIF ( I need JPG not PNG). The code I have does work MOST times but ... for some GIFs an orange tint is produced. My environment is: Win XP Java 1.4.2_03 JAI 1.1.2 --- today's version Ima

  • IOS7 update is now causing all phones to get all text messages

    I have an iphone, my son has an iphone and my other son has an ipod.  Since the iOS7 update, all the devices get the texts that anyone who text messages me from an iphone sends. How do I stop this? I have tried going on itunes to manage multiple acco

  • Treo 700wx problem

    a couple days ago my VZW 700wx was giving me the message that my storage space was becoming critically low. i deleted a few .cab files and put it away. i was also outside of available coverage range while this was occurring. about an hour after that