jueves, 1 de agosto de 2013

Utileria. Para poblar un pojo con datos provenientes de un resultSet.

Esta es una clase utileria para poblar un objeto DTO con datos provenientes de un resultset en java

package com.inditex.isu4.core.services.factory;

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

import org.apache.log4j.Logger;

/**
 * Factoria de construccion de DTO's
 * @author etereum
 *
 */
public class DTOFactory{

private static Logger log = Logger.getLogger(DTOFactory.class);

/**
* Contrulle la lista de DTO's apartir del tipo de dto que se pase como parametro.
* @param dtoType
* @param rs
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SecurityException
*/
public static <T> List<T> getDTOListFromRS(T dtoType, ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException{
log.debug("getDTOListFromRS....");
List<T> dataList = new ArrayList<T>();
Constructor[] factories = dtoType.getClass().getDeclaredConstructors();
Constructor factory = null;
for (int i = 0; i < factories.length; i++) {
factory = factories[i];
   if (factory.getGenericParameterTypes().length == 0)
break;
}
while(rs.next()){
   Object dto = factory.newInstance();
   Field[] props = dto.getClass().getDeclaredFields();
  for(Field prop:props){
 try{
Object value = rs.getObject(prop.getName());
  String methodName= "set";
      methodName += String.valueOf(prop.getName().charAt(0)).toUpperCase();
  methodName += prop.getName().substring(1);
  Class<?> classType =null;
  if(value ==null){
  continue;
  }else if(value instanceof String){
      classType=String.class;
  }else if(value instanceof Integer){
      classType=Integer.class;
  }else if(value instanceof Date){
  classType=Date.class;
  }
  Method setter = dto.getClass().getMethod(methodName, classType);
  setter.invoke(dto, value);
 }catch(Exception e){
 log.warn("No fue posible asignar el valor. ["+prop+"]");
   log.warn("Exception.getDTOListFromRS", e);
   }
           }
dataList.add((T)dto);
}
log.debug("getDTOListFromRS.OK.");
return dataList;
}

}

No hay comentarios:

Publicar un comentario