dbutil queryrunner 实现查询返回结果下划线转驼峰命名
当使用BeanListHandler时只需加上下面代码即可
QueryRunner runner=new QueryRunner(druidDataSource);
//开启驼峰映射
BeanProcessor bean = new GenerousBeanProcessor();
RowProcessor processor = new BasicRowProcessor(bean);
String sql="";
//此处Area传入列表需要的泛型
List<Area> list=runner.query(sql,new BeanListHandler<Area>(Area.class,processor))
当需要返回结果为List<Map<String,String>>时就需要我们自己写一个Handler了
此处贴出我自己写的类
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* 自定义QueryRunner 处理方法
* @author hang.zhong
* @date 2019.7.18
*/
public class CamelMapListHandler extends MapListHandler {
@Override
protected Map<String, Object> handleRow(ResultSet rs) throws SQLException {
Map<String, Object> result = new HashMap<>();
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
for(int i = 1; i <= cols; ++i) {
String columnName = rsmd.getColumnLabel(i);
if (null == columnName || 0 == columnName.length()) {
columnName = rsmd.getColumnName(i);
}
//此处CamelUndelineUtil为一个下划线转驼峰的工具,这种工具很简单,我就不贴出来了
result.put(CamelUndelineUtil.camel(columnName), rs.getObject(i));
}
return result;
}
}
使用时
QueryRunner runner=new QueryRunner(druidDataSource);
String sql="";
List<Map<String,Object>> list=runner.query(sql,new CamelMapListHandler(),null)