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
19
20 import java.beans.PropertyDescriptor;
21 import java.sql.ResultSetMetaData;
22 import java.sql.SQLException;
23 import java.util.Arrays;
24
25
26 /**
27 * Provides generous name matching (e.g. underscore-aware) from DB
28 * columns to Java Bean properties.
29 *
30 * @since 1.6
31 */
32 public class GenerousBeanProcessor extends BeanProcessor {
33
34 /**
35 * Default constructor.
36 */
37 public GenerousBeanProcessor() {
38 }
39
40 @Override
41 protected int[] mapColumnsToProperties(final ResultSetMetaData rsmd,
42 final PropertyDescriptor[] props) throws SQLException {
43
44 final int cols = rsmd.getColumnCount();
45 final int[] columnToProperty = new int[cols + 1];
46 Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);
47
48 for (int col = 1; col <= cols; col++) {
49 String columnName = rsmd.getColumnLabel(col);
50
51 if (null == columnName || 0 == columnName.length()) {
52 columnName = rsmd.getColumnName(col);
53 }
54
55 final String generousColumnName = columnName
56 .replace("_", "") // more idiomatic to Java
57 .replace(" ", ""); // can't have spaces in property names
58
59 for (int i = 0; i < props.length; i++) {
60 final String propName = props[i].getName();
61
62 // see if either the column name, or the generous one matches
63 if (columnName.equalsIgnoreCase(propName) ||
64 generousColumnName.equalsIgnoreCase(propName)) {
65 columnToProperty[col] = i;
66 break;
67 }
68 }
69 }
70
71 return columnToProperty;
72 }
73
74 }