View Javadoc

1   /*
2    * Created on Apr 6, 2005 by davidson
3    */
4   package ca.spaz.sql;
5   
6   import java.lang.reflect.Field;
7   import java.sql.*;
8   
9   /***
10   * Simple Java Object / Relational Database linker
11   * Uses reflection to map between simple objects and corresponding table rows.
12   * 
13   * @author davidson
14   */
15  public abstract class DBRow {
16     
17     /***
18      * Attempts to load all fields in the object from a ResultSet row.
19      * @param row a row in a database that corresponds directly to the object
20      * @throws SQLException
21      * @throws IllegalArgumentException
22      * @throws IllegalAccessException
23      */
24     public static void load(ResultSet row, Object obj)  throws SQLException, IllegalArgumentException, IllegalAccessException {
25        int cols = row.getMetaData().getColumnCount();
26  
27        Field[] fields = obj.getClass().getFields();
28        for (int i=0; i<fields.length; i++) {
29           String name = fields[i].getName();
30           Class type = fields[i].getType();
31           
32           if (type == String.class) {
33              fields[i].set(obj, row.getObject(name));
34           } else if (type == int.class) {
35              fields[i].setInt(obj, row.getInt(name));         
36           } else if (type == double.class) {
37              fields[i].setDouble(obj, row.getDouble(name));         
38           }
39        }
40     }
41  
42  
43  }