实现
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import javax.persistence.Column;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.jdbc.core.RowMapper;
public class DefaultRowMapper<T> implements RowMapper<T> {
Class<T> clazz;
Field[] allField ;
/**
* 构造函数
* @param clazz 实体类型
*/
public DefaultRowMapper(Class<T> clazz) {
this.clazz = clazz;
this.allField = clazz.getDeclaredFields();
}
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
try {
T tt = clazz.newInstance();
for (Field field : allField) {
Column column = field.getAnnotation(Column.class);
if (null == column) {
continue;
}
String columnName = column.name();
Class<?> type = field.getType();
try {
if (null == rs.getObject(columnName)) {
continue;
}
} catch (Exception e) {
continue;
}
if (String.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), rs.getString(columnName));
} else if (int.class.equals(type) || Integer.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), rs.getInt(columnName));
} else if (Date.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), new Date(rs.getDate(columnName).getTime()));
} else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), rs.getBoolean(columnName));
} else if (long.class.equals(type) || Long.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), rs.getLong(columnName));
} else if (double.class.equals(type) || Double.class.equals(type)) {
PropertyUtils.setProperty(tt, field.getName(), rs.getDouble(columnName));
} else {
PropertyUtils.setProperty(tt, field.getName(), rs.getObject(columnName));
}
}
return tt;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
调用
public class User implements Serializable{
private static final long serialVersionUID = -7789794961290885829L;
@Column(name="id")
private String id;
@Column(name="name")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
String sql = "select count(1) from t_user";
List<User> list=jdbcTemplate.query(sql, new DefaultRowMapper<User>(User.class));