Introduce DataClassRowMapper with record-style constructor binding support
Closes gh-24695
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -31,8 +31,9 @@ import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeanWrapper;
|
||||
import org.springframework.beans.BeanWrapperImpl;
|
||||
import org.springframework.beans.NotWritablePropertyException;
|
||||
import org.springframework.beans.PropertyAccessorFactory;
|
||||
import org.springframework.beans.TypeConverter;
|
||||
import org.springframework.beans.TypeMismatchException;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
@@ -114,8 +115,6 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
/**
|
||||
* Create a new {@code BeanPropertyRowMapper}, accepting unpopulated
|
||||
* properties in the target bean.
|
||||
* <p>Consider using the {@link #newInstance} factory method instead,
|
||||
* which allows for specifying the mapped type once only.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
*/
|
||||
public BeanPropertyRowMapper(Class<T> mappedClass) {
|
||||
@@ -222,8 +221,8 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
this.mappedClass = mappedClass;
|
||||
this.mappedFields = new HashMap<>();
|
||||
this.mappedProperties = new HashSet<>();
|
||||
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
|
||||
for (PropertyDescriptor pd : pds) {
|
||||
|
||||
for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(mappedClass)) {
|
||||
if (pd.getWriteMethod() != null) {
|
||||
this.mappedFields.put(lowerCaseName(pd.getName()), pd);
|
||||
String underscoredName = underscoreName(pd.getName());
|
||||
@@ -250,12 +249,12 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < name.length(); i++) {
|
||||
char s = name.charAt(i);
|
||||
if (Character.isUpperCase(s)) {
|
||||
result.append('_').append(Character.toLowerCase(s));
|
||||
char c = name.charAt(i);
|
||||
if (Character.isUpperCase(c)) {
|
||||
result.append('_').append(Character.toLowerCase(c));
|
||||
}
|
||||
else {
|
||||
result.append(s);
|
||||
result.append(c);
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
@@ -280,11 +279,12 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
*/
|
||||
@Override
|
||||
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
|
||||
Assert.state(this.mappedClass != null, "Mapped class was not specified");
|
||||
T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
|
||||
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
|
||||
BeanWrapperImpl bw = new BeanWrapperImpl();
|
||||
initBeanWrapper(bw);
|
||||
|
||||
T mappedObject = constructMappedInstance(rs, bw);
|
||||
bw.setBeanInstance(mappedObject);
|
||||
|
||||
ResultSetMetaData rsmd = rs.getMetaData();
|
||||
int columnCount = rsmd.getColumnCount();
|
||||
Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<>() : null);
|
||||
@@ -336,13 +336,25 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
|
||||
if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
|
||||
throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " +
|
||||
"necessary to populate object of class [" + this.mappedClass.getName() + "]: " +
|
||||
this.mappedProperties);
|
||||
"necessary to populate object of " + this.mappedClass + ": " + this.mappedProperties);
|
||||
}
|
||||
|
||||
return mappedObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an instance of the mapped class for the current row.
|
||||
* @param rs the ResultSet to map (pre-initialized for the current row)
|
||||
* @param tc a TypeConverter with this RowMapper's conversion service
|
||||
* @return a corresponding instance of the mapped class
|
||||
* @throws SQLException if an SQLException is encountered
|
||||
* @since 5.3
|
||||
*/
|
||||
protected T constructMappedInstance(ResultSet rs, TypeConverter tc) throws SQLException {
|
||||
Assert.state(this.mappedClass != null, "Mapped class was not specified");
|
||||
return BeanUtils.instantiateClass(this.mappedClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the given BeanWrapper to be used for row mapping.
|
||||
* To be called for each row.
|
||||
@@ -361,26 +373,42 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
|
||||
/**
|
||||
* Retrieve a JDBC object value for the specified column.
|
||||
* <p>The default implementation calls
|
||||
* {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}.
|
||||
* Subclasses may override this to check specific value types upfront,
|
||||
* or to post-process values return from {@code getResultSetValue}.
|
||||
* <p>The default implementation delegates to
|
||||
* {@link #getColumnValue(ResultSet, int, Class)}.
|
||||
* @param rs is the ResultSet holding the data
|
||||
* @param index is the column index
|
||||
* @param pd the bean property that each result object is expected to match
|
||||
* @return the Object value
|
||||
* @throws SQLException in case of extraction failure
|
||||
* @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)
|
||||
* @see #getColumnValue(ResultSet, int, Class)
|
||||
*/
|
||||
@Nullable
|
||||
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
|
||||
return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a JDBC object value for the specified column.
|
||||
* <p>The default implementation calls
|
||||
* {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}.
|
||||
* Subclasses may override this to check specific value types upfront,
|
||||
* or to post-process values return from {@code getResultSetValue}.
|
||||
* @param rs is the ResultSet holding the data
|
||||
* @param index is the column index
|
||||
* @param paramType the target parameter type
|
||||
* @return the Object value
|
||||
* @throws SQLException in case of extraction failure
|
||||
* @since 5.3
|
||||
* @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)
|
||||
*/
|
||||
@Nullable
|
||||
protected Object getColumnValue(ResultSet rs, int index, Class<?> paramType) throws SQLException {
|
||||
return JdbcUtils.getResultSetValue(rs, index, paramType);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code BeanPropertyRowMapper}
|
||||
* (with the mapped class specified only once).
|
||||
* Static factory method to create a new {@code BeanPropertyRowMapper}.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
* @see #newInstance(Class, ConversionService)
|
||||
*/
|
||||
@@ -389,8 +417,7 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code BeanPropertyRowMapper}
|
||||
* (with the required type specified only once).
|
||||
* Static factory method to create a new {@code BeanPropertyRowMapper}.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
* @param conversionService the {@link ConversionService} for binding
|
||||
* JDBC values to bean properties, or {@code null} for none
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.jdbc.core;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.TypeConverter;
|
||||
import org.springframework.core.DefaultParameterNameDiscoverer;
|
||||
import org.springframework.core.ParameterNameDiscoverer;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* {@link RowMapper} implementation that converts a row into a new instance
|
||||
* of the specified mapped target class. The mapped target class must be a
|
||||
* top-level class and may either expose a data class constructor with named
|
||||
* parameters corresponding to column names or classic bean property setters
|
||||
* (or even a combination of both).
|
||||
*
|
||||
* <p>Note that this class extends {@link BeanPropertyRowMapper} and can
|
||||
* therefore serve as a common choice for any mapped target class, flexibly
|
||||
* adapting to constructor style versus setter methods in the mapped class.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 5.3
|
||||
* @param <T> the result type
|
||||
*/
|
||||
public class DataClassRowMapper<T> extends BeanPropertyRowMapper<T> {
|
||||
|
||||
private static final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
|
||||
|
||||
@Nullable
|
||||
private Constructor<T> mappedConstructor;
|
||||
|
||||
@Nullable
|
||||
private String[] constructorParameterNames;
|
||||
|
||||
@Nullable
|
||||
private Class<?>[] constructorParameterTypes;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code DataClassRowMapper} for bean-style configuration.
|
||||
* @see #setMappedClass
|
||||
* @see #setConversionService
|
||||
*/
|
||||
public DataClassRowMapper() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@code DataClassRowMapper}.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
*/
|
||||
public DataClassRowMapper(Class<T> mappedClass) {
|
||||
super(mappedClass);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
protected void initialize(Class<T> mappedClass) {
|
||||
super.initialize(mappedClass);
|
||||
|
||||
this.mappedConstructor = BeanUtils.findPrimaryConstructor(mappedClass);
|
||||
|
||||
if (this.mappedConstructor == null) {
|
||||
Constructor<?>[] ctors = mappedClass.getConstructors();
|
||||
if (ctors.length == 1) {
|
||||
this.mappedConstructor = (Constructor<T>) ctors[0];
|
||||
}
|
||||
else {
|
||||
try {
|
||||
this.mappedConstructor = mappedClass.getDeclaredConstructor();
|
||||
}
|
||||
catch (NoSuchMethodException ex) {
|
||||
throw new IllegalStateException("No primary or default constructor found for " + mappedClass, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.mappedConstructor.getParameterCount() > 0) {
|
||||
this.constructorParameterNames = BeanUtils.getParameterNames(this.mappedConstructor);
|
||||
this.constructorParameterTypes = this.mappedConstructor.getParameterTypes();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T constructMappedInstance(ResultSet rs, TypeConverter tc) throws SQLException {
|
||||
Assert.state(this.mappedConstructor != null, "Mapped constructor was not initialized");
|
||||
|
||||
Object[] args;
|
||||
if (this.constructorParameterNames != null && this.constructorParameterTypes != null) {
|
||||
args = new Object[this.constructorParameterNames.length];
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String name = underscoreName(this.constructorParameterNames[i]);
|
||||
Class<?> type = this.constructorParameterTypes[i];
|
||||
args[i] = tc.convertIfNecessary(getColumnValue(rs, rs.findColumn(name), type), type);
|
||||
}
|
||||
}
|
||||
else {
|
||||
args = new Object[0];
|
||||
}
|
||||
|
||||
return BeanUtils.instantiateClass(this.mappedConstructor, args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code DataClassRowMapper}.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
* @see #newInstance(Class, ConversionService)
|
||||
*/
|
||||
public static <T> DataClassRowMapper<T> newInstance(Class<T> mappedClass) {
|
||||
return new DataClassRowMapper<>(mappedClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code DataClassRowMapper}.
|
||||
* @param mappedClass the class that each row should be mapped to
|
||||
* @param conversionService the {@link ConversionService} for binding
|
||||
* JDBC values to bean properties, or {@code null} for none
|
||||
* @see #newInstance(Class)
|
||||
* @see #setConversionService
|
||||
*/
|
||||
public static <T> DataClassRowMapper<T> newInstance(
|
||||
Class<T> mappedClass, @Nullable ConversionService conversionService) {
|
||||
|
||||
DataClassRowMapper<T> rowMapper = newInstance(mappedClass);
|
||||
rowMapper.setConversionService(conversionService);
|
||||
return rowMapper;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -62,8 +62,6 @@ public class SingleColumnRowMapper<T> implements RowMapper<T> {
|
||||
|
||||
/**
|
||||
* Create a new {@code SingleColumnRowMapper}.
|
||||
* <p>Consider using the {@link #newInstance} factory method instead,
|
||||
* which allows for specifying the required type once only.
|
||||
* @param requiredType the type that each result object is expected to match
|
||||
*/
|
||||
public SingleColumnRowMapper(Class<T> requiredType) {
|
||||
@@ -216,8 +214,7 @@ public class SingleColumnRowMapper<T> implements RowMapper<T> {
|
||||
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code SingleColumnRowMapper}
|
||||
* (with the required type specified only once).
|
||||
* Static factory method to create a new {@code SingleColumnRowMapper}.
|
||||
* @param requiredType the type that each result object is expected to match
|
||||
* @since 4.1
|
||||
* @see #newInstance(Class, ConversionService)
|
||||
@@ -227,8 +224,7 @@ public class SingleColumnRowMapper<T> implements RowMapper<T> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Static factory method to create a new {@code SingleColumnRowMapper}
|
||||
* (with the required type specified only once).
|
||||
* Static factory method to create a new {@code SingleColumnRowMapper}.
|
||||
* @param requiredType the type that each result object is expected to match
|
||||
* @param conversionService the {@link ConversionService} for converting a
|
||||
* fetched value, or {@code null} for none
|
||||
|
||||
Reference in New Issue
Block a user