Introduce DataClassRowMapper with record-style constructor binding support

Closes gh-24695
This commit is contained in:
Juergen Hoeller
2020-08-28 18:52:35 +02:00
parent d4192b9d35
commit d37eaa5941
10 changed files with 388 additions and 80 deletions

View File

@@ -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

View File

@@ -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;
}
}

View File

@@ -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

View File

@@ -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.
@@ -25,7 +25,10 @@ import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.ConstructorPerson;
import org.springframework.jdbc.core.test.DatePerson;
import org.springframework.jdbc.core.test.Person;
import org.springframework.jdbc.core.test.SpacePerson;
@@ -48,32 +51,50 @@ import static org.mockito.Mockito.verify;
*/
public abstract class AbstractRowMapperTests {
protected void verifyPerson(Person bean) throws Exception {
assertThat(bean.getName()).isEqualTo("Bubba");
assertThat(bean.getAge()).isEqualTo(22L);
assertThat(bean.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56"));
protected void verifyPerson(Person person) {
assertThat(person.getName()).isEqualTo("Bubba");
assertThat(person.getAge()).isEqualTo(22L);
assertThat(person.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(person.getBalance()).isEqualTo(new BigDecimal("1234.56"));
verifyPersonViaBeanWrapper(person);
}
protected void verifyPerson(ConcretePerson bean) throws Exception {
assertThat(bean.getName()).isEqualTo("Bubba");
assertThat(bean.getAge()).isEqualTo(22L);
assertThat(bean.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56"));
protected void verifyPerson(ConcretePerson person) {
assertThat(person.getName()).isEqualTo("Bubba");
assertThat(person.getAge()).isEqualTo(22L);
assertThat(person.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(person.getBalance()).isEqualTo(new BigDecimal("1234.56"));
verifyPersonViaBeanWrapper(person);
}
protected void verifyPerson(SpacePerson bean) {
assertThat(bean.getLastName()).isEqualTo("Bubba");
assertThat(bean.getAge()).isEqualTo(22L);
assertThat(bean.getBirthDate()).isEqualTo(new Timestamp(1221222L).toLocalDateTime());
assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56"));
protected void verifyPerson(SpacePerson person) {
assertThat(person.getLastName()).isEqualTo("Bubba");
assertThat(person.getAge()).isEqualTo(22L);
assertThat(person.getBirthDate()).isEqualTo(new Timestamp(1221222L).toLocalDateTime());
assertThat(person.getBalance()).isEqualTo(new BigDecimal("1234.56"));
}
protected void verifyPerson(DatePerson bean) {
assertThat(bean.getLastName()).isEqualTo("Bubba");
assertThat(bean.getAge()).isEqualTo(22L);
assertThat(bean.getBirthDate()).isEqualTo(new java.sql.Date(1221222L).toLocalDate());
assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56"));
protected void verifyPerson(DatePerson person) {
assertThat(person.getLastName()).isEqualTo("Bubba");
assertThat(person.getAge()).isEqualTo(22L);
assertThat(person.getBirthDate()).isEqualTo(new java.sql.Date(1221222L).toLocalDate());
assertThat(person.getBalance()).isEqualTo(new BigDecimal("1234.56"));
}
protected void verifyPerson(ConstructorPerson person) {
assertThat(person.name()).isEqualTo("Bubba");
assertThat(person.age()).isEqualTo(22L);
assertThat(person.birth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(person.balance()).isEqualTo(new BigDecimal("1234.56"));
verifyPersonViaBeanWrapper(person);
}
private void verifyPersonViaBeanWrapper(Object person) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(person);
assertThat(bw.getPropertyValue("name")).isEqualTo("Bubba");
assertThat(bw.getPropertyValue("age")).isEqualTo(22L);
assertThat((Date) bw.getPropertyValue("birth_date")).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L));
assertThat(bw.getPropertyValue("balance")).isEqualTo(new BigDecimal("1234.56"));
}
@@ -123,6 +144,11 @@ public abstract class AbstractRowMapperTests {
given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");
given(resultSet.findColumn("name")).willReturn(1);
given(resultSet.findColumn("age")).willReturn(2);
given(resultSet.findColumn("birth_date")).willReturn(3);
given(resultSet.findColumn("balance")).willReturn(4);
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());

View File

@@ -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.
@@ -37,9 +37,8 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*/
public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings({"unchecked", "rawtypes"})
public void testOverridingDifferentClassDefinedForMapping() {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->

View File

@@ -0,0 +1,45 @@
/*
* 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.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.test.ConstructorPerson;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
* @since 5.3
*/
public class DataClassRowMapperTests extends AbstractRowMapperTests {
@Test
public void testStaticQueryWithDataClass() throws Exception {
Mock mock = new Mock();
List<ConstructorPerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new DataClassRowMapper<>(ConstructorPerson.class));
assertThat(result.size()).isEqualTo(1);
verifyPerson(result.get(0));
mock.verifyClosed();
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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.test;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author Juergen Hoeller
*/
public class ConstructorPerson {
private String name;
private long age;
private java.util.Date birth_date;
private BigDecimal balance;
public ConstructorPerson(String name, long age, Date birth_date, BigDecimal balance) {
this.name = name;
this.age = age;
this.birth_date = birth_date;
this.balance = balance;
}
public String name() {
return name;
}
public long age() {
return age;
}
public Date birth_date() {
return birth_date;
}
public BigDecimal balance() {
return balance;
}
}