Skip to content

Commit ed7bb8b

Browse files
committed
simpilfy JavaBeanMapper slightly
1 parent 39700fd commit ed7bb8b

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

mug-guava/src/main/java/com/google/mu/safesql/JavaBeanMapper.java

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -61,45 +61,40 @@ static <T> Optional<ResultMapper<T>> ofBeanClass(Class<T> beanClass) {
6161

6262
@Override T from(ResultSet row) throws SQLException {
6363
ImmutableSet<String> columnNames = getCanonicalColumnNames(row.getMetaData());
64-
T bean;
6564
try {
66-
bean = defaultConstructor.newInstance();
65+
T bean = defaultConstructor.newInstance();
66+
if (columnNames.size() >= setters.size()) { // full population
67+
for (Map.Entry<String, Populator> property : setters.entrySet()) {
68+
property.getValue().populate(bean, row, property.getKey());
69+
}
70+
} else { // sparsely populate from the columns
71+
for (String name : columnNames) {
72+
Populator populator = setters.get(name);
73+
checkArgument(
74+
populator != null,
75+
"No settable property is defined by %s for column %s", beanClass, name);
76+
populator.populate(bean, row, name);
77+
}
78+
}
79+
return bean;
6780
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
6881
throw new VerifyException(e);
6982
}
70-
if (columnNames.size() >= setters.size()) { // full population
71-
for (Map.Entry<String, Populator> property : setters.entrySet()) {
72-
property.getValue().populate(bean, row, property.getKey());
73-
}
74-
} else { // sparsely populate from the columns
75-
for (String name : columnNames) {
76-
Populator populator = setters.get(name);
77-
checkArgument(
78-
populator != null,
79-
"No settable property is defined by %s for column %s", beanClass, name);
80-
populator.populate(bean, row, name);
81-
}
82-
}
83-
return bean;
8483
}
8584

8685
private interface Populator {
87-
void populate(Object bean, ResultSet row, String columnName) throws SQLException;
86+
void populate(Object bean, ResultSet row, String columnName)
87+
throws SQLException, InvocationTargetException, IllegalAccessException;
8888

8989
static Populator of(PropertyDescriptor property) {
9090
Method setter = requireNonNull(property.getWriteMethod());
9191
setter.setAccessible(true);
9292
Class<?> type = property.getPropertyType();
9393
return (bean, row, columnName) -> {
9494
Object value = row.getObject(columnName, Primitives.wrap(type));
95-
if (value == null && type.isPrimitive()) {
96-
// for primitive, if the value is null, don't call setter.
97-
return;
98-
}
99-
try {
95+
// for primitive, if the value is null, don't call setter.
96+
if (value != null || !type.isPrimitive()) {
10097
setter.invoke(bean, value);
101-
} catch (InvocationTargetException | IllegalAccessException e) {
102-
throw new VerifyException(e);
10398
}
10499
};
105100
}

0 commit comments

Comments
 (0)