在项目中采用Ibatis作为访问持久层框架时,有时我们又需要启用JDBC连接来完成某种意义上的操作,而把Ibatis的开发模式更改了又不是我们的初衷,因此我们只能在已经用sqlMap.xml配置好的基础上进行参数封装。
具体参数方法如下:
/**
* 预编译封装对象
* @param sqlmap
* @param ps
* @param sqlId
* @param params
* @return 绘制PreparedStatement
*/
public static PreparedStatement getSqlParameterMap(SqlMapClientImpl sqlmap,PreparedStatement ps,String sqlId,Object params) {
/**获取ibatis参数*/
ParameterMapping[]paramMappSet = getParameterMapp( sqlmap, sqlId);
/**反射来装配参数*/
try {
int index=0;
for(ParameterMapping paramMapp : paramMappSet){
index++;
String methodName = "get"+toFirstLetterUpperCase(paramMapp.getPropertyName());
Method method = params.getClass().getDeclaredMethod(methodName);
Object obj = null;
obj = method.invoke(params, null);
putPreparedStatement(ps,index,obj ,method.getGenericReturnType());
}
} catch (Exception e) {
new Result(Const.RS_ERROR,"","反射装配ibatais参数异常,系统错误!",(Params)params,e,log);
}
return ps;
}
/**
* 获取ibatis预编译参数
* */
private static ParameterMapping[] getParameterMapp(SqlMapClientImpl sqlmap,String sqlId){
/**获取sqlMap.xml映射*/
MappedStatement stmt = sqlmap.getMappedStatement(sqlId);
/**获取指定ID的parameterClass参数*/
ParameterMapping[] paramMappSet = stmt.getParameterMap().getParameterMappings();
return paramMappSet;
}
private static void putPreparedStatement(PreparedStatement ps,int index,Object obj ,Object type) throws SQLException{
/*String*/
if(obj instanceof String){
ps.setString(index, obj.toString());
}
/*Integer*/
if(obj instanceof Integer){
ps.setInt(index, Integer.valueOf(obj.toString()));
}
/*Long*/
if(obj instanceof Long){
ps.setLong(index, Long.valueOf(obj.toString()));
}
/*Double*/
if(obj instanceof Double){
ps.setDouble(index, Double.valueOf(obj.toString()));
}
/*Date*/
if(obj instanceof Date){
}
if(obj instanceof BigDecimal){
ps.setBigDecimal(index, BigDecimal.valueOf(Long.valueOf(obj.toString())));
}
}
//**
* 将手字母大写
**/
public static String toFirstLetterUpperCase(String strName) {
if (strName == null || strName.length() < 2) {
return strName;
}
String firstLetter = strName.substring(0, 1).toUpperCase();
return firstLetter + strName.substring(1, strName.length());
}