SpringJDBC:RowMapper通用类:泛型

实现

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));

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值