Populated nested collections

Say I have two database tables, users and widgets. A user may have 0 or many widgets. So the tables look like this:
users:
userId   username
  1       One
  2       Two
  3       Threewidgets:
widgetId   userId
  1          2
  2          3
  3          3So this means user One has 0 widgets, user Two has 1 widget and user Three has 2 widgets
So I want to map this data into Java, so I have an Object like this
public class User {
    private int id;
    private String name;
    private Set widgets = new LinkedHashSet();
    //Assume getters and setters for id and name
    public void addWidget(Integer widgetId) {
        widgets.add(widgetId);
}Then I have JDBC code that executes this query:
  SELECT u.userId as id, u.username as name, w.widgetId
    FROM users u, widgets w
   WHERE u.userId = w.userId(+)
ORDER BY u.useridThis would get the widgets for a each user. You need the outer join because I still want to create a User object even if the user has no widgets. So the result from the query is:
id  name   widgetId
1  One
2  Two     1
3  Three   2
3  Three   3So then I want to have code that goes through the ResultSet and create a Set of User objects, one object for each user with the widgets Set of each User object populated with the widgetIds. The contents of the Set would be like this:
id=[1],name=[One],widgets=[]
id=[2],name=[Two],widgets=[[1]]
id=[3],name=[Three],widgets=[[2],[3]]But my question is how do you get that? If you do this:
//This will hold the Users
Set set = new LinkedHashSet();
//Assume ps is a PreparedStatement that will get the ResultSet
ResultSet rs = ps.executeQuery();
//This will hold each User
User user = null;
while(rs.next()) {
    user = new User();
    user.setId(rs.getInt("id"));
    user.setName(rs.getString("name"));
    user.addWidget(new Integer(rs.getInt("widgetId")));
    set.add(user);
}That will get 2 user objects for user 3. I could create the equals() and hashCode() methods for User, but then how can I call addWidget() on the user that is already in the set when I get to the 2nd record in the ResultSet for user 3? Should I do this? (replace the set.add(user) from above with this)
//Assuming I have the equals() and hashCode() methods for User
//set.add() will return false if the user is already in the set
if(!set.add(user)) {
    Iterator i = set.iterator();
    User tmpUser = null;
    while(i.hasNext()) {
        tmpUser = (User)i.next();
        if(user.equals(tmpUser) {
            tmpUser.addWidget(rs.getInt("widgetId"));
            break;
}Would that even work? Is there a better way?

OR or or or
you use join so you have unique key (u.userId) so you can do this on the server side(and this is very good idea) as you don this before
using yours query:
SELECT u.userId as id, u.username as name, w.widgetId
FROM users u, widgets w
WHERE u.userId = w.userId(+)
ORDER BY u.userid
you have always sorted data so you do not have to use hashMap , you should write simple state machine
private static User prevUser;
Integer tmpInt;
while (rs.next()) {
     user = new User();
     user.setId(rs.getInt("id"));
     user.setName(rs.getString("name"));
     // simple temporary buffer because rs.getInt("widgetId") should be readed only once  
        tmpInt = new Integer(rs.getInt("widgetId"));
      * This is your state machine
      * for the first  loop prevUser = null so
      * user.equals(prevUser) will return fals
         * you have to do the check in your equals method in User class
     if (user.equals(prevUser)) {
          prevUser.addWidget(tmpInt);
     } else {
          user.addWidget(tmpInt);
          set.add(user);
          prevUser = user;
public class User {
* equals method in User class
public boolean equals(User myUser) {
     if (myUser == null)
          return false;
     else if (this.id == myUser.getId())
          return true;
     return false;
} // end of User classgood luck

Similar Messages

  • XSU: Nested Collections?

    Does anyone know of a way to get around Oracle's limitation on nested collections?
    I have been using XSU to present XML to our Java application layer using objects and object views. Casting multisets works fine for repeating elements as long as the elements themselves don't contain repeating elements. I have been able to get around this with nested cursors, but I am not sure that XSU was designed to work this way. I get a nasty error if any of the cursors return an empty set.
    Example:
    SELECT
    company_name,
    CURSOR(SELECT
    dept_name,
    CURSOR(SELECT
    group_name
    FROM group_table g
    WHERE g.dept_id = d.dept_id) AS "GROUPS"
    FROM
    dept_table d
    WHERE
    d.company_id = c.company_id) AS "DEPARTMENTS"
    FROM company_table c
    If any of the above cursors returns an empty set then I get the following error:
    oracle.xml.sql.OracleXMLSQLException: Closed Statement: oracle.jdbc.oci8.OCIDBStatement@18f375
    Anyone gotten around this another way?

    Hi Christopher,
    I posted a similar question before. I even don't know how to create such a table to store XML data.
    Like your example
    <company>
    <dept>
    <group>
    <emp>
    </emp>
    </group>
    <group>
    </group>
    </dept>
    <dept>
    </dept>
    </company>
    Do you know how to create a table to store this kind of xml data with several hierarchical levels?
    null

  • Nested Collections In Bridge?

    Is it possible to create nested collections in Bridge? I've looked in the help file, but can't find any mention. Don't know if I'm missing it or it just can't be done.
    Thanks,
    Chuck

    Collection is not folder it is just the file that is created in the bridge preferences to ease out the navigation for the user.
    Go to C:\Users\<user name>\AppData\Roaming\Adobe\Bridge CS5\Collections
    you will find the filelist files ther with the name of your collection, if you open those file in the wordpard you will see the path of the files included in the collection.
    hence I dont think the nested collection could be created becuase we cannot refer the filelist file in another filelist file.

  • Locking objects in nested collections

    Hi,
    I am looking at having a data store in memory which will be made up of nested collections e.g. a hashmap whose values are hashmaps. This data store will be accessed by multiple threads and to avoid threading issues on updates I realize I have to implement some form of locking. However I don't want to coarse grain lock the data store for all accesses when updating and I would prefer to lock on a more finer grained level.
    My question is this, is it possible to place a lock on an object in a collection or those the entire collection have to be locked e.g. given a hashmap within a hashmap is it possible to lock the inner hashmap and not the outer.
    regards
    Noel

    I don't think there could be any issue. Get the object from the hash map and lock it. But the Object should have synchronized methods to handle multiple threads, So that when multiple threads get reference to the same object from the hash map they get a synchronized access to the data or logic in the Object.

  • Printing nested collections

    I have a struts application and trying to display a nested collection. For example, I have an arraylist of Persons object which in turn has a collection of Accounts object. Whats the syntax for iterating through the nested collection using the tags like
    <logic:iterate id="item" name="myList" scope="request" >
    <bean:write name="item" property="firstName"/>
    * How do I iterate through the nested collection of Accounts here
    </logic:terate>
    I want to avoid writing scriplets for the same.
    Thanks

    Collection is not folder it is just the file that is created in the bridge preferences to ease out the navigation for the user.
    Go to C:\Users\<user name>\AppData\Roaming\Adobe\Bridge CS5\Collections
    you will find the filelist files ther with the name of your collection, if you open those file in the wordpard you will see the path of the files included in the collection.
    hence I dont think the nested collection could be created becuase we cannot refer the filelist file in another filelist file.

  • How to migrate nested collections?

    In our SCCM 2007 environment we have dozens of nested collections, some are 4 or 5 collections deep too.   How do you migrate that over to CM2012?   In a lab environment I tried to migrate the collection.
    TestCollection\One Deep\Two Deep\Three Deep
    Each of the 4 collection had a machine inside of it. the migration wizard worked but I don't see my collections in the CM2012 console.
    mqh7

    The Collections should be migrated, ususally it's a refresh of the console that is required to see the new folders and Collections. One thing you can do to verify the migration is checking the "objects in job" status. It will provide you with information
    about the success/failure of the migration. You can also check the migmctl.log file for detailed information about the process.
    Kent Agerlund | My blogs: blog.coretech.dk/kea and
    SCUG.dk/ | Twitter:
    @Agerlund | Linkedin: Kent Agerlund |
    Mastering ConfigMgr 2012 The Fundamentals

  • UIX DataControl : Nested Collection Help Please

    Hello all,
    I am developing an app using the ff. evironment:
    IDE: JDeveloper 9052
    UI: ADF UIX
    Core: EJB
    1. I have a Session Bean that returns a collection of a POJO containing 2 POJOs and a collection of another POJO.
    2. I created a DataControl for the Session bean, set the bean class (in the XML datacontrol) as well as the Collection type for the other property. ?I am wondering how to set the bean property for the collection elements?.
    3. I then dragged the return for each of the POJOs and collection contained in the collection onto my UIX page as a read-only table. The return values for POJOs in the collection were rendered but the return values for the nested collection is not, I can only see a table with empty rows and columns .
    This is the collection class:
    public class NestedCollection {
    public nestedCollection(){
    private Pojo1 pojo1;
    private Pojo2 pojo2;
    private Collection nestedOne;
    //...accessor methods
    What is the workaround for this?

    Found it. I did not recompile. gee

  • [svn:bz-4.0.0_fixes] 20615: fixing the regression failure caused by the nest collection level fix, an actionscript type without remote alias will resolved as " className", we should filter out the special case

    Revision: 20615
    Revision: 20615
    Author:   [email protected]
    Date:     2011-03-04 12:11:09 -0800 (Fri, 04 Mar 2011)
    Log Message:
    fixing the regression failure caused by the nest collection level fix, an actionscript type without remote alias will resolved as ">className", we should filter out the special case
    Modified Paths:
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/AmfIO.java

    Remember that Arch Arm is a different distribution, but we try to bend the rules and provide limited support for them.  This may or may not be unique to Arch Arm, so you might try asking on their forums as well.

  • [svn:bz-4.0.0_fixes] 20586: backporting nest object level fix and nest collection level fix from blazeds trunk to 4 .0.0.fixes branch

    Revision: 20586
    Revision: 20586
    Author:   [email protected]
    Date:     2011-03-03 13:44:51 -0800 (Thu, 03 Mar 2011)
    Log Message:
    backporting nest object level fix and nest collection level fix from blazeds trunk to 4.0.0.fixes branch
    checkintests pass
    Modified Paths:
        blazeds/branches/4.0.0_fixes/modules/common/src/flex/messaging/errors.properties
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/endpoints/AbstractEndpoint.j ava
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/SerializationContext.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf0Input.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf0Output.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf3Input.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf3Output.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/AmfIO.java

    Revision: 20586
    Revision: 20586
    Author:   [email protected]
    Date:     2011-03-03 13:44:51 -0800 (Thu, 03 Mar 2011)
    Log Message:
    backporting nest object level fix and nest collection level fix from blazeds trunk to 4.0.0.fixes branch
    checkintests pass
    Modified Paths:
        blazeds/branches/4.0.0_fixes/modules/common/src/flex/messaging/errors.properties
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/endpoints/AbstractEndpoint.j ava
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/SerializationContext.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf0Input.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf0Output.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf3Input.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/Amf3Output.java
        blazeds/branches/4.0.0_fixes/modules/core/src/flex/messaging/io/amf/AmfIO.java

  • Generic Dump Nested Collection Procedure?

    Greetings,
    Anyone have a proc which when passed a (possibly deeply) nested collection will dump a pretty-printed representation via dbms_output?
    I know this is a mostly just a typing exercise using recursion, but
    1. my PL/SQL skills apparently aren't up to the task
    2. I don't see any kind of get_type() function for the dump proc to use to decide how to loop through sub-collections
    so I'd like to see how the experts do it.
    Am using 10g.
    Thanks,
    --jim
    example:
    DECLARE
      TYPE numset_t IS TABLE OF NUMBER;
      TYPE numset_t_aa IS TABLE OF numset_t INDEX BY VARCHAR2(16);
      TYPE numset_t_aa_v IS VARRAY(2) OF numset_t_aa;
      n_aa numset_t_aa;
      n_t_aa_v numset_t_aa_v;
    BEGIN
      n_aa('tens') := numset_t(10,11,12);
      n_aa('ones') := numset_t(1,2,3);
      n_t_aa_v(1) := n_aa;
      n_aa.DELETE('ones');
      SELECT * BULK COLLECT INTO n_aa('hundreds') FROM table(numset_t(103,102,101));
      n_t_aa_v(2) := n_aa;
      dbms_output('dumping n_t_aa_v:');
      dump_collection(n_t_aa_v);
    END;expected output:
    dumping dumping n_t_aa_v:
    1:
      tens:
        1: 10
        2: 11
        3: 12
      ones:
        1: 1
        2: 2
        3: 3
    2:
      tens:
        1: 10
        2: 11
        3: 12
      hundreds:
        1: 103
        2: 102
        3: 101

    Hi,
    Why are you using collections in the first place?
    If the sole purpose here is to generate XML, then you don't need collection at all, just query your base tables with SQL/XML functions.
    If these collections are part of a larger process (besides generating XML), then you'll need to use at least SQL types instead of local PL/SQL types if you want to efficiently generate XML out of them.
    For example, using the XMLType constructor over the topmost object : {message:id=10012696}

  • Exported nested collection only saving schema, not data?

    Robin proposed an answer of exporting multiple collections into one:
    http://social.technet.microsoft.com/Forums/en-US/3c55b873-a0c7-4cc8-9bab-eaf809f62ab0/exporting-data?forum=projectsiena
    It seems to work as long as you immediately import - this is because the collection is still in memory.  If you exit the app (or clear the collection), then only the schema can be loaded because the data itself isn't saved.
    When I look into the .zip file, I see that the schema is being written but no underlying data.
    Perhaps I'm doing something wrong and that's why I'm only getting the schema?
    I would be happy to share the project I've been working on if that would be helpful.
    Thanks!
    Thor

    thorwm,
       I was initially experiencing the same issue, but it turns out I was just confused (again).   I was building the nested collection during the OnSelect event for the Export control.   Apparently, the OnSelect event happens
    AFTER the Export control performs the export.   This can be seen by simply doing the export twice.  
       I have to look at a better way to perform the nested collection process.   Hopefully this is the same issue you are experiencing.
    -Bruton

  • Populating the "Collections" drop down list in FEP reports

    When an FEP Antimalware report (e.g., the Antimalware Activity Report) opens in Report Manager or the FEP console, I see a drop-down list labeled
    Collection: from which I need to make a selection before the report can run.  But on our site, this drop-down list is not populated, even though ConfigMgr shows that collections do exist on our site.
    The report is running under credentials that should have full access to everything in the relevant databases, so I'm puzzled.  Any suggestions?

    This old post and there are a lot of improvements in FEP's successor which is System Center Endpoint Protection (SCEP), you may try use SCEP and try reproduce the problem and if problem persist let us know.
    Sometimes, it is issue due to SQL database , so check SQL and make sure it is working correctly and is fully updated.

  • Populating a collection with function results

    I am calculating some statistics and need to use a collection to store the results of several function so they can be used in a procedure. Example:
    PROCEDURE PRODUCTIVITY_INSERT(p_first_of_month IN DATE)
    AS
    BEGIN
    vc_FirstofMonth := p_first_of_month;
    FOR i IN 1..3 loop
    EXECUTE IMMEDIATE 'INSERT INTO RFC_BUS'||days(i)||'PRODUCTIVITY(ROUTE,PPPH)
    SELECT a.route, ((sr05 / sy05)/'||counts(i)||') AS "RATIO"
    FROM (SELECT route,
    SUM (DECODE (TO_CHAR (pick, "MM-YYYY"),
    to_char(vc_FirstofMonth, "MM-YYYY"), platform_hours, null)) AS sy05
    FROM bus_platformhours
    WHERE day_type ='||days(i)||' and platform_hours > 0
    GROUP BY route) a,
    (SELECT route,
    SUM (DECODE (TO_CHAR (service_date, "mm-yyyy"),
    to_char(vc_FirstofMonth, "MM-YYYY"), rides, null)) AS sr05
    FROM bush_daily_rides
    WHERE day_type = '||days(i)||
    'GROUP BY route) b
    WHERE a.route = b.route
    ORDER BY a.route
    VALUES(
    p_route,
    p_ratio
    ) USING days(i), counts(i)';
    end loop;
    Can I use collections to hold the function results (say three function out variables) while they are being looped through in the procedure? If I can do that I am presuming I use the functions name in the collection such as:
    TYPE dayoneList IS TABLE OF NUMBER;
    dayone dayoneList := dayoneList(wkdaysminusone(), sadaysminusone(), sudaysminusone());
    thanks for any help you can give me.

    Do you mean to use the functions as the elements of collection constructor ?
    It's possible:
    SQL> create function get_one return number is begin return 1; end;
      2  /
    Function created.
    SQL> create function get_two return number is begin return 2; end;
      2  /
    Function created.
    SQL> declare
      2   type arr is table of number;
      3   arr1 arr := arr(get_one(), get_two());
      4  begin
      5   for i in 1..arr1.count loop
      6    dbms_output.put_line(arr1(i));
      7   end loop;
      8  end;
      9  /
    1
    2
    PL/SQL procedure successfully completed.Rgds.

  • AD Site names are not populated in Collection criteria drop down menu...

    I tried to create a collection based on AD Site name. Collection creating wizard on the membership rules tab, query rule properties, edit query statement (system resource), criteria tab, criterion type is simple value, System resource - Active
    Directory site name, operatör is equal to Vlaue... there is no AD site names appear in this drop down menu, just one of the 20 sites appear. I already run the system discovery, and create Automatically boundary for the each sites. And also create
    the Bpoundary groups...
    Thanks,

    Yes, I know this is an old post, but I’m trying to clean them up.
    Did you solve this problem, if so what was the solution?
    Without the query that you are using it will be hard to troubleshoot this issue but my guess is that the PC that belong to those AD site have not yet be inventoried. Check your Heartbeat and Hardware inventory.
    Garth Jones | My blogs: Enhansoft and
    Old Blog site | Twitter:
    @GarthMJ

  • How can I avoid "NoSuch ElementException"  by nested collections

    I have been getting NoSuchElementException being thrown when iterating through nested HashSet. the code is as follows:
    for(int cols = 0; cols < arr.length; cols++){
          System.out.println("running for column " + cols);
          arrTemp1 = arr[cols];
          System.out.println("total size of template set "+ arrTemp1.size()+" for column "+cols);
          arrTemp2 = arr[cols+1];
          Iterator it1 = arrTemp1.iterator();
          Iterator it2 = arrTemp2.iterator();
          while(it1.hasNext()){
               String s = (it1.next()).toString();
               //System.out.println("printing template "+ s);
            String detector = s;
            while (it2.hasNext()){     
                 String sLeft = getLeftChild(s);
                 //System.out.println("left child of template "+ sLeft);
                 String sRight = getRightChild(s);
                 //System.out.println("right child of template "+ sRight);
                 if(sLeft.equals((it2.next()).toString())){
                     detector += sLeft.substring((sLeft.length() - 1));
                     System.out.println("detector "+ detector+" created from child "+ sLeft);
                 }else if(sRight.equals((it2.next()).toString())){
                     detector += sRight.substring((sRight.length() - 1));
                     System.out.println("detector "+ detector+" created from child "+ sRight);
               }//end while  
               if (detector.length() == noBits){
                System.out.println("detector "+ detector+" created from "+ s);     
                detectors.add(detector);       
          }//end while     
         }//end for     

    for(int cols = 0; cols < arr.length; cols++){
       arrTemp2 = arr[cols+1]; // cols+1 = arr.length !!!!

Maybe you are looking for

  • Pages preview fine in DW, but CSS appears to be ignored on live website

    This is very basic, but I can't figure it out.  I am the successor webmaster for a very simple 15-page website.   The site has some layout issues that need correcting, and I have rewritten the pages using more of a CSS-based layout since (among other

  • PDF file not showing context

    After upgrading to ML I have recived a PDF that if I open with Preview only shows me part of the info (layout tables and bullets) but the text does not show! The text works for the windows users and I can see it in OmniGraffle. Anyone an idea what's

  • LCD as opposed to LED

    Could someone help me to understand the difference between LCD and LED? I understand that my I-mac has a 24 inch wide active matrix LCD display. I read somewhere that the LED ones do not have mercury, etc. and are supposedly "safer" to use than LCD.

  • Account receivable from sap bw perspective

    hi,    this is viswa.my client is asked is account receivable analysis from SAP BW perspective. Thanks & Regards, viswa.

  • ORA-00923:FROM KEYWORD NOT FOUND WHERE EXPECTED

    I have nade a oracle ODBC TO MS-EXCEL.While writting query in microsoft query editor I got the error msg ORA-00923:FROM KEYWORD NOT FOUND WHERE EXPECTED The following query runs fine on sql plus editior wht could be the reason ,pls guide me select OR