项目场景:
最近的一个项目没有用到mybatis此类ORM框架,所以在做实体类映射时会出现一些比较冗余以及难看的代码,比如:requestDMO.setWorkOrderNo(requestInfo.get("WORKORDER_NO"));
requestDMO.setFromStatus(requestInfo.get("ORDER_STATE"));
requestDMO.setOrderState(requestInfo.get("ORDER_STATE"));
requestDMO.setToStatus(requestInfo.get("ORDER_STATE"));
所以做了一个简单的工具类来做映射处理。
下划线转驼峰格式:
首先是将下划线转驼峰形式,比如:TEST_FIELD==>testField
public static String formatAttr(String dbfield) {
if (dbfield.indexOf('_') < 0) {
return dbfield.toLowerCase();
}
dbfield = dbfield.toLowerCase();
StringTokenizer stk = new StringTokenizer(dbfield, "_");
String attrField = "";
int p = 0;
while (stk.hasMoreTokens()) {
if (p == 0) {
attrField = stk.nextToken();
}
else {
attrField += captureName(stk.nextToken());
}
p++;
}
return attrField;
}
/**
* Description:首字母大写 <br>
*
* @author liu.yasu<br>
* @taskId <br>
* @param name <br>
* @return <br>
*/
public static String captureName(String name) {
char[] cs = name.toCharArray();
cs[0] -= 32;
return String.valueOf(cs);
}
编写测试main方法之后,可以看到已经进行了转换:
进行实体类映射:
有了上面的工具后就可以做相应的实体映射了,代码如下:
public static void populateMap(Object bean, Map<String, String> mMap)
throws InvocationTargetException, IllegalAccessException {
Iterator<String> iterator = mMap.keySet().iterator();
Map tempMap = new HashMap();
while (iterator.hasNext()) {
String key = iterator.next();
Object val = mMap.get(key);
if (!(val instanceof String || val instanceof Date || val instanceof Integer)) {
continue;
}
tempMap.put(formatAttr(key), val);
}
BeanUtils.populate(bean, tempMap);
}