com.mario6.common.db.mapper.BeanRowMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spring-jdbc Show documentation
Show all versions of spring-jdbc Show documentation
一个简单的jdbc封装库,大多数api接口与spring-jdbc类似
The newest version!
package com.mario6.common.db.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
/**
* 通过反射获得对应POJO对象
*
* 注:反射对象类型必须拥有一个默认构造函数
* @param
*/
public class BeanRowMapper implements RowMapper {
private boolean snake;
private Class beanClazz;
private BeanRowMapper(Class beanClazz, boolean snake) {
this.beanClazz = beanClazz;
this.snake = snake;
}
public static BeanRowMapper newInstance(Class clazz, boolean snake) {
return new BeanRowMapper(clazz, snake);
}
public static BeanRowMapper newInstantce(Class clazz) {
return new BeanRowMapper(clazz,false);
}
@Override
public T rowMap(ResultSet rs) throws SQLException {
ClassInfo classInfo = ClassInfo.newInstance(beanClazz, false);
List.FieldInfo> fields = classInfo.getFieldsInfo();
T obj = classInfo.createByDefaultConstructor();
for (ClassInfo.FieldInfo field : fields) {
String column = field.getName(snake);
Class type = convertType(field.getType());
Object value = rs.getObject(column, type);
field.setValue(obj, value);
}
return obj;
}
private Class convertType(Class orig) {
Class type = orig;
if(type == java.util.Date.class) {
type = Timestamp.class;
}
return type;
}
};