|
1、通过传入预执行sql和封装好的model,解析sql,实现类似mybatis的半自动化功能
2、代码:
public static boolean updateSql(String sql, Object value) {
//解析#{xxx}字符串,其中xxx是JavaBean的字段,实现思路是解析里面的属性,通过反射获取value中的值
int start = sql.indexOf("#{");
int end = sql.indexOf("}");
List<Object> vals = new ArrayList<Object>();
while (start >-1 && end > start) {
//#{userName} - ? #{userPw}
//userName -> getUserName
String wholeProp = sql.substring(start, end+1);
String subProp = wholeProp.substring(2, wholeProp.length()-1);
sql = sql.replace(wholeProp, " ? ");
String methodName = "get" + subProp.substring(0,1).toUpperCase() + subProp.substring(1);
Method method = null;
try {
method = value.getClass().getDeclaredMethod(methodName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
vals.add(method.invoke(value));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
start = sql.indexOf("#{");
end = sql.indexOf("}");
}
Connection conn = DbUtils.getConnection();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for (int i = 0 ; i < vals.size(); i++) {
ps.setObject(i+1, vals.get(i));
}
ps.execute();
return true;
} catch (SQLException e) {
return false;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}
}
3、测试代码:
String sql = " update news set "
+ " title = #{title},"
+ " info = #{info} "
+ " where id = #{id}";
Object obj = DaoUtils.initEntity(News.class, request);
boolean result = DaoUtils.updateSql(sql, obj);
|
|