08 März 2013

JDBC: Using POJOs in SQL Queries Result Mapping Simplyfied

... and because it worked so well with JPA I created a result mapper for JDBC:

public class JdbcSqlResultMapper {

  public static <T> List<T> list(ResultSet rs, Class<T> clazz) 
    throws SQLException {
    List<T> result = new ArrayList<T>();
    Constructor<?> ctor = 
      (Constructor<?>) clazz.getDeclaredConstructors()[0];
    while (rs.next()) {
      Object[] objs = 
        new Object[ctor.getParameterTypes().length];
      for (int i = 0; i < ctor.getParameterTypes().length; i++) {
        objs[i] = rs.getObject(i + 1);
      }
      createAndAddBean(ctor, objs, result);
    }
    return result;
}

  private static <T> void createAndAddBean(
    Constructor<?> ctor, Object[] args, List<T> result) {
    try {
      T obj = (T) ctor.newInstance(args);
      result.add(obj);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}


Keine Kommentare: