insert daoSupport

本文介绍了使用Java反射和BeanUtils工具将对象转换为Map,然后通过自定义的dbRouter和jdbcDaoSupport进行数据库插入操作的过程。重点在于对象与数据库之间的映射关系,以及如何高效地实现数据的增删改查。



public static Map po2Map(Object po) {
Map poMap = new HashMap();
Map map = new HashMap();
try {
map = BeanUtils.describe(po);
} catch (Exception ex) {
}
Object[] keyArray = map.keySet().toArray();
for (int i = 0; i < keyArray.length; i++) {
String str = keyArray[i].toString();
if (str != null && !str.equals("class")) {
if (map.get(str) != null) {
poMap.put(str, map.get(str));
}
}
}

Method[] ms =po.getClass().getMethods();
for(Method m:ms){
String name = m.getName();

if(name.startsWith("get")){
if(m.getAnnotation(NotDbField.class)!=null){
poMap.remove(getFieldName(name));
}
}

}
return poMap;
}

public void insert(String table, Object po) {

Map poMap = ReflectionUtil.po2Map(po);

table = this.dbRouter.getTableName( table);
this.jdbcDaoSupport.insert(table, poMap);
}
public void insert(String table, Map fields) {
String sql = "";

try {

Assert.hasText(table, "表名不能为空");
Assert.notEmpty(fields, "字段不能为空");
table = quoteCol(table);

Object[] cols = fields.keySet().toArray();
Object[] values = new Object[cols.length];
for (int i = 0; i < cols.length; i++) {
if (fields.get(cols[i]) == null) {
values[i] = null;
} else {
values[i] = fields.get(cols[i]).toString();
}
cols[i] = quoteCol(cols[i].toString());
}

sql = "INSERT INTO " + table + " ("
+ StringUtil.implode(", ", cols) + ") VALUES ("
+ StringUtil.implodeValue(", ", values) + ")";

jdbcTemplate.update(sql, values);
} catch (Exception e) {
e.printStackTrace();
throw new DBRuntimeException(e, sql);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值