GenerousBeanProcessor.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.dbutils;


  18. import java.beans.PropertyDescriptor;
  19. import java.sql.ResultSetMetaData;
  20. import java.sql.SQLException;
  21. import java.util.Arrays;


  22. /**
  23.  * Provides generous name matching (e.g. underscore-aware) from DB
  24.  * columns to Java Bean properties.
  25.  *
  26.  * @since 1.6
  27.  */
  28. public class GenerousBeanProcessor extends BeanProcessor {

  29.     /**
  30.      * Default constructor.
  31.      */
  32.     public GenerousBeanProcessor() {
  33.     }

  34.     @Override
  35.     protected int[] mapColumnsToProperties(final ResultSetMetaData rsmd,
  36.             final PropertyDescriptor[] props) throws SQLException {

  37.         final int cols = rsmd.getColumnCount();
  38.         final int[] columnToProperty = new int[cols + 1];
  39.         Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

  40.         for (int col = 1; col <= cols; col++) {
  41.             String columnName = rsmd.getColumnLabel(col);

  42.             if (null == columnName || 0 == columnName.length()) {
  43.                 columnName = rsmd.getColumnName(col);
  44.             }

  45.             final String generousColumnName = columnName
  46.                     .replace("_", "")   // more idiomatic to Java
  47.                     .replace(" ", "");  // can't have spaces in property names

  48.             for (int i = 0; i < props.length; i++) {
  49.                 final String propName = props[i].getName();

  50.                 // see if either the column name, or the generous one matches
  51.                 if (columnName.equalsIgnoreCase(propName) ||
  52.                         generousColumnName.equalsIgnoreCase(propName)) {
  53.                     columnToProperty[col] = i;
  54.                     break;
  55.                 }
  56.             }
  57.         }

  58.         return columnToProperty;
  59.     }

  60. }