在MyEclipse中怎么把RowMapper做成泛型接口?

 我来答
  • 你的回答被采纳后将获得:
  • 系统奖励15(财富值+成长值)+难题奖励30(财富值+成长值)
听风8kBD5
2017-02-15
知道答主
回答量:61
采纳率:0%
帮助的人:6.1万
展开全部
package com.hundsun.cc.kms.dao.mapper;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.ReflectionUtils;

import com.hundsun.cc.kms.common.KMSRuntimeException;

public class CommonRowMapper<T> implements RowMapper<T> {
private static final Logger logger = LoggerFactory.getLogger(CommonRowMapper.class);

private Class<T> cls;
public CommonRowMapper(Class<T> cls) {
this.cls = cls;
}
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
try {
T rowObj = (T)this.cls.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
int count=metaData.getColumnCount();

for(int i=1;i<=count;i++) {
String columnName = StringUtils.lowerCase(metaData.getColumnName(i));
Field field = ReflectionUtils.findField(this.cls, columnName);
if(field == null) {
field = ReflectionUtils.findField(this.cls, underlineToCamelhump(columnName));
}
if(field != null) {
ReflectionUtils.makeAccessible(field);
Class type = field.getType();
if(type == Integer.class || type == int.class) {
ReflectionUtils.setField(field, rowObj, rs.getInt(i));
}
if(type == String.class) {
ReflectionUtils.setField(field, rowObj, rs.getString(i));
}
if(type == Long.class || type == long.class) {
ReflectionUtils.setField(field, rowObj, rs.getLong(i));
}
}
}
return rowObj;
} catch (InstantiationException e) {
logger.error("实例化类(" + cls.getName() + ")报错",e);
throw new KMSRuntimeException("实例化类(" + cls.getName() + ")报错");
} catch (IllegalAccessException e) {
logger.error("非法访问权限(" + cls.getName() + ")",e);
throw new KMSRuntimeException("非法访问权限(" + cls.getName() + ")");
}
}

// 将下划线风格替换为驼峰风格
public static String underlineToCamelhump(String str) {
Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
StringBuilder builder = new StringBuilder(str);
for (int i = 0; matcher.find(); i++) {
builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
}
if (Character.isUpperCase(builder.charAt(0))) {
builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
}
return builder.toString();
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式