公司的ERP强于业务逻辑,疏于技术。数据库查询竟然是继承了javax.swing.table.DefaultTableModel的鬼东西
尽管不能容忍,但全盘重构得要one year。这样的活谁愿意干,原有的程序员也都已经喜欢躺在这种模式中了。
那就先利用Mybatis对新的代码开发、维护想点办法吧。
DefaultTableModel中包含数据的列信息和数据信息。MyBatis通过resultType或者resultMap 或者自定义TypeHandler都无法满足。需要使用MyBatis的Interceptor进行处理。其使用步骤有两步:
1.定义拦截器插件
2.注册拦截器
定义拦截器:(以下用自定义的类型MyType01进行了模拟)
public class ResultPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
Statement statement = (Statement) args[0];
ResultSet rs = statement.getResultSet();
ResultSetMetaData rsMetaData = rs.getMetaData();
MyType01 myType01 = new MyType01();
Map<String, String> fieldInfo = new HashMap<String, String>();
myType01.setFieldInfo(fieldInfo);
System.out.println(rsMetaData);
for (int i = 0; i < rsMetaData.getColumnCount(); i++) {
String columnName = rsMetaData.getColumnName(i + 1);
String columnClassName = rsMetaData.getColumnClassName(i + 1);
fieldInfo.put(columnName, columnClassName);
System.out.println(columnName + ":" + columnClassName);
}
while (rs == null) {
if (statement.getMoreResults()) {
rs = statement.getResultSet();
} else {
if (statement.getUpdateCount() == -1) {
break;
}
}
}
Set<String> keySet = fieldInfo.keySet();
List<Map<String, ?>> result = new ArrayList<Map<String, ?>>();
myType01.setResult(result);
if (rs != null) {
while (rs.next()) {
Map<String, String> row = new HashMap<String, String>();
result.add(row);
Iterator<String> fieldNames = keySet.iterator();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
String fieldValue = rs.getString(fieldName);
row.put(fieldName, fieldValue);
System.out.print(fieldName + "=" + fieldValue);
}
System.out.println();
}
}
return Arrays.asList(myType01);
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
注册拦截器
<configuration>
<plugins>
<plugin interceptor="com.ebitg.mybatis.ResultPlugin">
</plugin>
</plugins>
</configuration>
image.png
打完收工....
网友评论