Search code examples
javacollectionsjdbcresultset

Building resultset using collection object


I had an issue in building the resultset using Java.

I am storing a collection object which is organized as row wise taken from a resultset object and putting the collection object (which is stored as vector/array list) in cache and trying to retrieve the same collection object.

Here I need to build back the resultset again using the collection object. Now my doubt is building the resultset in this way possible or not?


Solution

  • The best idea if you are using a collection in place of a cache is to use a CachedRowSet instead of a ResultSet. CachedRowSet is a Subinterface of ResultSet, but the data is already cached. This is far simpler than to write all the data into an ArrayList.
    CachedRowSets can also be queried themselves.

    CachedRowSet rs;
    .......................
    .......................
    Integer id;
    String name;
    
    while (rs.next())
    {               
         if (rs.getInt("id") == 13)
         {
              id   = rs.getInt("id");
              name = rs.getString("name")); 
         }              
    }
    

    So you just call the CachedRowSet whenever you need the info. It's almost as good as sliced bread. :)

    EDIT:
    There are no set methods for ResultSet, while there are Update methods. The problem with using the Update method's for the purpose of rebuilding a ResultSet is that it requires selecting a Row to update. Once the ResultSet has freed itself, all rows are set to null. A null reference cannot be called. A List of Lists mimics a ResultSet itself, or more correctly, an array of arrays mimic a ResultSet.

    While Vectors are thread safe, there is a huge overhead attached to them. Use the ArrayList instead. As each nested List is created and placed into the outer nest List, insert it in this manner.

    nest.add(Collections.unmodifiableList(nested));
    

    After all of the nested Lists are inserted, return the nest List as an umodifiableList as well. This will give you a thread-safe collection without the overhead of the vectors.