Package com.reflectiondao.dao

Source Code of com.reflectiondao.dao.TemplateResultSetExtractor

package com.reflectiondao.dao;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.reflectiondao.annotation.DatabaseField;


/**
* The Class TemplateResultSetExtractor.
*
* @param <S>
*            the generic type
*/
public class TemplateResultSetExtractor<S> implements ResultSetExtractor<S> {

  /** The type. */
  private Class<S> type;

  /**
   * Instantiates a new template result set extractor.
   *
   * @param type
   *            the type
   */
  public TemplateResultSetExtractor(Class<S> type) {
    this.type = type;
  }

  /* (non-Javadoc)
   * @see org.springframework.jdbc.core.ResultSetExtractor#extractData(java.sql.ResultSet)
   */
  @Override
  public S extractData(ResultSet rs) throws SQLException, DataAccessException {
    try {

      List<Object> params = new ArrayList<Object>();

      for (Field f : this.type.getDeclaredFields()) {
        DatabaseField db = f.getAnnotation(DatabaseField.class);

        params.add(db.type().getValue(f, rs));

      }

      @SuppressWarnings("unchecked")
      Constructor<S> ctor = (Constructor<S>) this.type.getConstructors()[0];

      /*
       * TODO check all constructors for the one that is closest to
       * ctor.getParameterTypes() May want to use distance calculations
       */

      S object = ctor.newInstance(params.toArray());

      return object;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

}
TOP

Related Classes of com.reflectiondao.dao.TemplateResultSetExtractor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.