spring jdbc mapper

本文介绍了一种使用 Java 的 JDBC 进行数据库操作的方法,通过自定义 AutoInject 类实现对象到数据库记录的映射,简化了数据访问层的开发工作。此方法利用反射机制动态创建对象,并填充从数据库中获取的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class BaseDao {
private JdbcTemplate jdbcTemplate;
public <T> List<T> queryAll(String sql,Object[] args,Class<T> clazz){
List<T> result = new ArrayList<T>();
AutoInject<T> inject = new AutoInject.Builder<T>().build(clazz);
RowMapper<T> mapper = new RowMapperImpl<T>(inject);
result = jdbcTemplate.query(sql, args, mapper);
mapper = null;
inject = null;
return result;
}

}

public class AutoInject<T> {
private ResultSetMetaData metaData;
private int count;
private String[] columnNames;
private Class<T> clazz;
public static class Builder<T>{
public AutoInject<T> build(Class<T> clazz){
return new AutoInject<T>(clazz);
}
}
public AutoInject(Class<T> clazz){
this.clazz = clazz;
}
public void init(ResultSet rs) throws SQLException{
if (metaData == null){
metaData = rs.getMetaData();
count = metaData.getColumnCount();
columnNames = new String[count];
initColumnNames();
}
}
private void initColumnNames() throws SQLException{
Field[] fields = clazz.getDeclaredFields();
String temp = null;
for (int i = 0; i < columnNames.length;i++){
temp = metaData.getColumnName(i + 1);
for (int j = 0; j < fields.length; j++){
if (temp.equalsIgnoreCase(fields[j].getName())){
columnNames[i] = fields[j].getName();
break;
}
}
}
}
public T mapRow(ResultSet rs){
Field field = null;
T result = null;
try {
result = clazz.newInstance();
for (String name : columnNames){
field = clazz.getDeclaredField(name);
field.setAccessible(true);
field.set(result, rs.getObject(name));
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return result;
}
}

public class RowMapperImpl<T> implements RowMapper<T> {
private AutoInject<T> inject;
public RowMapperImpl(AutoInject<T> inject){
this.inject = inject;
}
@Override
public T mapRow(ResultSet rs, int arg1) throws SQLException {
inject.init(rs);
T t = inject.mapRow(rs);
return t;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值