package org.theonefx.wcframework.jdbc; import java.lang.reflect.Field; import java.security.AccessController; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.theonefx.wcframework.core.ClassWrapper; import org.theonefx.wcframework.core.inject.Injector; import org.theonefx.wcframework.jdbc.annotation.Column; import org.theonefx.wcframework.jdbc.exception.NotSupportedTypeException; import org.theonefx.wcframework.jdbc.exception.RowMapperException; import org.theonefx.wcframework.utils.StringUtils; public class SimpleBeanRowMapper<T> implements RowMapper<T> { private final Class<T> clazz; private final Map<String, Injector> injectors = new HashMap<String, Injector>(); private final Map<String, Field> fieldInfos = new HashMap<String, Field>(); public SimpleBeanRowMapper(Class<T> clazz) { this.clazz = clazz; ClassWrapper<T> wrapper = ClassWrapper.getWrapper(clazz); Field[] fields = wrapper.getFields(); for (Field field : fields) { Column columnInfo = field.getAnnotation(Column.class); if (columnInfo != null && columnInfo.mapped() == false) { continue; } String fieldName = field.getName(); if (columnInfo != null && StringUtils.isNotBlank(columnInfo.column())) { fieldName = columnInfo.column(); } Injector injector = wrapper.getInjector(field.getName()); injectors.put(fieldName, injector); fieldInfos.put(fieldName, field); } } @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { T o = null; try { o = clazz.newInstance(); Iterator<Entry<String, Injector>> iter = injectors.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Injector> entry = iter.next(); String fieldName = entry.getKey(); Field field = fieldInfos.get(fieldName); ClassWrapper<?> typewrapper = ClassWrapper.getWrapper(field.getType()); Object value = null; if (typewrapper.isBoolean()) { value = rs.getBoolean(fieldName); } else if (typewrapper.isInt()) { value = rs.getInt(fieldName); } else if (typewrapper.isLong()) { value = rs.getLong(fieldName); } else if (typewrapper.isDouble()) { value = rs.getDouble(fieldName); } else if (typewrapper.isFloat()) { value = rs.getFloat(fieldName); } else if (typewrapper.isChar()) { value = rs.getShort(fieldName); } else if (typewrapper.isShort()) { value = rs.getShort(fieldName); } else if (typewrapper.isDateTimeLike()) { value = rs.getTimestamp(fieldName); } else if (typewrapper.isStringLike()) { value = rs.getString(fieldName); } else { value = rs.getObject(entry.getKey()); throw new NotSupportedTypeException("不支持的BeanMap类型:"+field.getType()); } entry.getValue().inject(o, value, AccessController.getContext()); } } catch (Exception e) { throw new RowMapperException("Class:" + clazz, e); } return afterCreate(o); } protected T afterCreate(T t) { return t; } }