views:

110

answers:

6

I'm new to java and just getting into querying databases. so far I have my results in a ResultSetMetaData. I'm think that for each row in the dataset I should add it to some form of collection? Can anyone tell me the best practice for this?

thanks,

Jonesy

+3  A: 

A List seems quite logical. If you are not going to be having duplicates, and you are not bothered about the order of the results, then perhaps a Set.

A relevant implementation of List:

  • ArrayList: This is backed by an array, so lookups on particular indices should be quick

Relevant implementations of Set:

  • HashSet: Backed by a HashMap so O(1) insertion time
  • TreeSet: Respects the ordering of the data (using the compareTo method) - so iterating over the data will be in order - the trade off is O(log n) insertion time
Noel M
+1  A: 

You can create class which represents real world entities. Later if you wish to choose ORM technology/tool like hibernate you can use same classes.

Shekhar
+6  A: 

Create an object to hold the data. Loop through the resultset, creating an object for each one, and store them in an ArrayList or HashMap, depending on how you want to use the data. This allows you to close the database, and it gives you good objects on which you can build methods to manipulate the data.

It also allows you to write code that uses the object that doesn't need to rely on the database. If you ever want to pull out the database later and switch to text files or whatever, it's easy to do and you can still use the same objects and methods.

Erick Robertson
thanks Erick. I have a table of users. I've made a class called DisplayUsers with a constructor to retrieve the users. for each user returned should I create a new object of class User for example?
iamjonesy
Yeah, something that has the same properties as the fields in the database table makes sense. Also, typically, the object has a name very similar to the name of the database table. I use a separate database class which implements source interfaces for the data types I want to pull. But I use the database very heavily for lots of different modules and I want to be source-agnostic.
Erick Robertson
+1  A: 

First, the ResultSetMetaData class holds "information about the types and properties of the columns in a ResultSet object." So the results from your query are in the ResultSet, not in the ResultSetMetaData object.

You can see the Retrieving Values from Result Sets Java tutorial for information on how to extract your data from a ResultSet. You should be able to just loop through the ResultSet as shown and put your records in a List or Map, depending on how you want to access the data later.

Bill the Lizard
+2  A: 

Usually we have a class with fields that correspond to a table. Then, whenever we have a (full) row in a result set, we create an instance of this class.

Example:

Consider a table created like this:

CREATE TABLE customer (First_Name char(50), Last_Name char(50),
   Address char(50), City char(50), Country char(25), Birth_Date date);

A model class would be like this:

public class Customer {
  private String firstName;
  private String lastName;
  private String address;
  private String city;
  private String country;
  private Date date;


  public String getFirstName() {
    return firstName;
  }
  // getters for all fields

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  // setters for all fields

  public String toString() {
    return String.format("[%s, %s, %s, %s, %s, %s]", firstName,
             lastName, address, city, country, date);
  }
}

Now if you read data and have a ResultSet, you would create a new customer object and set the fields:

List<Customer> customers = new ArrayList<Customer>();
ResultSet rs = stmt.executeQuery("SELECT * from CUSTOMER;");
while (rs.next()) {
  Customer customer = new Customer();
  customer.setFirstName(rs.get("First_Name"));
  // ... and so on

  customers.add(customer);
}
Andreas_D
in this situation does the query have to be within the same class as the object creation code?
iamjonesy
No, but I would design it that way, unless the application is that large that separating query and creation of model instances. The list can be created elsewhere, just added it there to show a brief and quite complete snippet.
Andreas_D
ok thanks, another question if you don't mind. Once I have created an object of each record. what sort of things can I do with that object? typically that is..
iamjonesy
you can present the data on a view (form, table, ...) or create an editor to modify existing db table rows (via the model object) or create new table entries.
Andreas_D
thanks last question i swear! I loop through each row creating the object then adding it to a an ArrayList. I then close the database connection. I know wanna access my objects through the ArrayList. how do i do this? I can only seem to print out the objects location
iamjonesy
Implement `toString` if you want `System.out.println(model)` to give a useful result. I've edited my code for a basic to show a simple implementation.
Andreas_D
thanks so how would i loop through each object and display, say, the firstname only. then again with the first and last?
iamjonesy
Just call the six getter methods (I've already added an implementation for the firstName field, the rest is the same pattern). We usually do not loop through the model fields, we call the getters. (last answer here - please open new questions on SO :-) )
Andreas_D
thanks for your help Andreas!
iamjonesy
A: 

I usually follow the same pattern as Andreas_D describes.

The object used to contain each row of data (in this case, the Customer class) is referred to as Data Transfer Object (TO).

The code that gets the database connection, queries the db, populates the TOs and returns them (typically in a List), is referred to as a Data Access Object (DAO).

You can read more about this design pattern here