User Tools

Site Tools


technical_notes:public:java-jdbc-helper-create-dto

Parent

Java - Jdbc Helper - Create Dto from ResultSet

Usage

ResultSet rs = preparedStatement.executeQuery("SELECT * FROM USER");
rs.next();
UserDto user = this.jdbcHelper.createFromResultSet(UserDto.class, rs);
UserDto.java
package sql.migrations;
public class UserDto {
	public int idUtilisateur;
        public String login;
}

Le champs idUtilisateur s'adresse au champs ID_UTILISATEUR de la base de donnée.

Jdbc Helper

package sql.migrations;
 
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
public class JdbcHelper {
	public <T> T createFromResultSet(Class<T> clazzOfT, ResultSet rs) throws InstantiationException,
			IllegalAccessException, IllegalArgumentException, SQLException {
		T result = clazzOfT.newInstance();
		Field[] fields = clazzOfT.getFields();
 
		for (Field field : fields) {
			String method = field.getName();
			String fieldName = this.getDatabaseFieldName(method);
			Class<?> fieldType = field.getType();
			try {
				if (fieldType == String.class) {
					field.set(result, rs.getString(fieldName));
				} else if (fieldType == int.class) {
					field.set(result, rs.getInt(fieldName));
				}
			} catch (SQLException ex) {
				throw new SQLException(String.format("Column %s invalid", fieldName), ex);
			}
		}
 
		return result;
	}
 
	private String getDatabaseFieldName(String method) {
		char[] characters = method.toCharArray();
		List<Character> field_name = new ArrayList<Character>(0);
		for (char character : characters) {
			if (Character.isUpperCase(character)) {
				field_name.add('_');
			}
			field_name.add(Character.toUpperCase(character));
		}
 
		return this.getStringRepresentation(field_name);
	}
 
	private String getStringRepresentation(List<Character> list) {
		StringBuilder builder = new StringBuilder(list.size());
		for (Character ch : list) {
			builder.append(ch);
		}
		return builder.toString();
	}
}
technical_notes/public/java-jdbc-helper-create-dto.txt · Last modified: 2015/01/21 13:28 by Fabien Arcellier