Commons DbUtils很一个很好用JDBC工具类,地球人都知道,就不介绍了,不知道的看这里:http://commons.apache.org/dbutils/
在进行查询自动类映射的时候domain类的属性必须和数据库中名称一样,但是如果数据库的表名使用带下划线的设计,domain类中的属性也要使用下划线,看起来很不雅观,而且使用hibernate工具自动生成的domain类会自动去掉下划线,下划线后面的用大写字母,比如user_name转换后为userName,因此有必要让DbUtils支持这种设计。
好,目标已经明确,下来就是开工了!
1、下载DbUtils的源代码
2、找到commons-dbutils-1.2-src\src\java\org\apache\commons\dbutils下的BeanProcessor.java,增加一个函数,代码如下:
- private String getPropertyName(String columnName){
- StringBuilder sb = new StringBuilder();
- boolean match =false;
- for (int i=0; i<columnName.length(); i++){
- char ch = columnName.charAt(i);
- if (match && ch>=97 && ch<=122)
- ch -= 32;
- if (ch!='_'){
- match = false;
- sb.append(ch);
- }else{
- match = true;
- }
- }
- return sb.toString();
- }
修改mapColumnsToProperties函数,红色部分是修改的地方。
- protectedint[] mapColumnsToProperties(ResultSetMetaData rsmd,
- PropertyDescriptor[] props) throws SQLException {
- int cols = rsmd.getColumnCount();
- int columnToProperty[] =newint[cols +1];
- Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
- for (int col =1; col <= cols; col++) {
- String columnName = <SPAN style="COLOR: #ff0000"><STRONG>getPropertyName(rsmd.getColumnName(col));</STRONG></SPAN>
- for (int i =0; i < props.length; i++) {
- if (columnName.equalsIgnoreCase(props[i].getName())) {
- columnToProperty[col] = i;
- break;
- }
- }
- }
- return columnToProperty;
- }
DButils的 1.3版本似乎已经修正了这个bug了吧,sql中可以使用别名来避免。
- protectedint[] mapColumnsToProperties(ResultSetMetaData rsmd,
- PropertyDescriptor[] props) throws SQLException {
- int cols = rsmd.getColumnCount();
- int columnToProperty[] =newint[cols +1];
- Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
- for (int col =1; col <= cols; col++) {
- //已经改过来为getColumnLabel了
- String columnName = rsmd.getColumnLabel(col);
- if (null == columnName ||0 == columnName.length()) {
- columnName = rsmd.getColumnName(col);
- }
- for (int i =0; i < props.length; i++) {
- if (columnName.equalsIgnoreCase(props[i].getName())) {
- columnToProperty[col] = i;
- break;
- }
- }
- }
- return columnToProperty;
- }
/**
* 根据雇员编码获取一个雇员 若放回null,则为找到
*/
public Employee getEmployeeByCode(int empCode) throws ApplicationException,
SQLException {
Connection conn = OracleDBUtils.getConnection();
// 为了处理表里字段的下划线 与javabean属性对应,CustomBeanProcessor继承了BeanProcessor,
// 并且重写BeanProcessor里方法mapColumnsToProperties
CustomBeanProcessor convert = new CustomBeanProcessor();
RowProcessor rp = new BasicRowProcessor(convert);
Object[] params = { empCode };
ResultSetHandler<Employee> rsh = new BeanHandler<Employee>(
Employee.class, rp);
return qr.query(conn, SQL_GET_EMPLOYEE_BYCODE, rsh, params);
}
本文详细介绍了如何使用DbUtils解决查询自动类映射时,domain类属性与数据库表名中下划线设计不一致的问题。通过自定义BeanProcessor类并重写相关方法,使得DbUtils能够正确处理带下划线的属性名,从而避免了属性名的不一致导致的映射错误。同时,文章提到了DButils的1.3版本可能已经修正了此bug,并提供了一个SQL别名作为替代方案。
801

被折叠的 条评论
为什么被折叠?



