Skip to content

Handle custom conversions for collections. #2081

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data Relational Parent</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-jdbc-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
4 changes: 2 additions & 2 deletions spring-data-jdbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-data-jdbc</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>

<name>Spring Data JDBC</name>
<description>Spring Data module for JDBC repositories.</description>
Expand All @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>
</parent>

<properties>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,11 @@ public JdbcValue writeJdbcValue(@Nullable Object value, TypeInformation<?> colum
}

Class<?> componentType = convertedValue.getClass().getComponentType();

if (componentType != byte.class && componentType != Byte.class) {

Object[] objectArray = requireObjectArray(convertedValue);

return JdbcValue.of(typeFactory.createArray(objectArray), JDBCType.ARRAY);
}

Expand All @@ -268,6 +270,21 @@ public JdbcValue writeJdbcValue(@Nullable Object value, TypeInformation<?> colum
return JdbcValue.of(convertedValue, JDBCType.BINARY);
}

/**
* Unwraps values of type {@link JdbcValue}.
*
* @param convertedValue a value that might need unwrapping.
*/
@Override
@Nullable
protected Object unwrap(@Nullable Object convertedValue) {

if (convertedValue instanceof JdbcValue jdbcValue) {
return jdbcValue.getValue();
}
return convertedValue;
}

@SuppressWarnings("unchecked")
@Override
public <R> R readAndResolve(TypeInformation<R> type, RowDocument source, Identifier identifier) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@
import org.springframework.data.jdbc.core.mapping.JdbcValue;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.jdbc.repository.support.JdbcRepositoryFactory;
import org.springframework.data.jdbc.testing.EnabledOnFeature;
import org.springframework.data.jdbc.testing.IntegrationTest;
import org.springframework.data.jdbc.testing.TestConfiguration;
import org.springframework.data.jdbc.testing.TestDatabaseFeatures;
import org.springframework.data.repository.CrudRepository;

/**
Expand All @@ -61,6 +63,11 @@ EntityWithStringyBigDecimalRepository repository(JdbcRepositoryFactory factory)
return factory.getRepository(EntityWithStringyBigDecimalRepository.class);
}

@Bean
EntityWithDirectionsRepository repositoryWithDirections(JdbcRepositoryFactory factory) {
return factory.getRepository(EntityWithDirectionsRepository.class);
}

@Bean
JdbcCustomConversions jdbcCustomConversions() {
return new JdbcCustomConversions(asList(StringToBigDecimalConverter.INSTANCE, BigDecimalToString.INSTANCE,
Expand All @@ -70,6 +77,7 @@ JdbcCustomConversions jdbcCustomConversions() {
}

@Autowired EntityWithStringyBigDecimalRepository repository;
@Autowired EntityWithDirectionsRepository repositoryWithDirections;

/**
* In PostrgreSQL this fails if a simple converter like the following is used.
Expand Down Expand Up @@ -162,6 +170,18 @@ void queryByEnumTypeEqual() {
.containsExactly(Direction.CENTER);
}

@Test // GH-2078
@EnabledOnFeature(TestDatabaseFeatures.Feature.SUPPORTS_ARRAYS)
void saveAndLoadListOfDirectionsAsArray() {

EntityWithDirections saved = repositoryWithDirections
.save(new EntityWithDirections(null, List.of(Direction.CENTER, Direction.RIGHT)));

EntityWithDirections reloaded = repositoryWithDirections.findById(saved.id).orElseThrow();

assertThat(reloaded).isEqualTo(saved);
}

interface EntityWithStringyBigDecimalRepository extends CrudRepository<EntityWithStringyBigDecimal, CustomId> {

@Query("SELECT * FROM ENTITY_WITH_STRINGY_BIG_DECIMAL WHERE DIRECTION IN (:types)")
Expand All @@ -171,6 +191,8 @@ interface EntityWithStringyBigDecimalRepository extends CrudRepository<EntityWit
List<EntityWithStringyBigDecimal> findByEnumType(Direction type);
}

interface EntityWithDirectionsRepository extends CrudRepository<EntityWithDirections, Long> {}

private static class EntityWithStringyBigDecimal {

@Id CustomId id;
Expand All @@ -194,6 +216,9 @@ private static class OtherEntity {
Date created;
}

record EntityWithDirections(@Id Long id, List<Direction> directions) {
}

enum Direction {
LEFT, CENTER, RIGHT
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
CREATE TABLE ENTITY_WITH_STRINGY_BIG_DECIMAL ( id IDENTITY PRIMARY KEY, Stringy_number DECIMAL(20,10), DIRECTION INTEGER);
CREATE TABLE OTHER_ENTITY ( ID IDENTITY PRIMARY KEY, CREATED DATE, ENTITY_WITH_STRINGY_BIG_DECIMAL INTEGER);
CREATE TABLE ENTITY_WITH_DIRECTIONS ( ID IDENTITY PRIMARY KEY, DIRECTIONS INTEGER ARRAY);
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
CREATE TABLE ENTITY_WITH_STRINGY_BIG_DECIMAL ( id IDENTITY PRIMARY KEY, Stringy_number DECIMAL(20,10), DIRECTION INTEGER);
CREATE TABLE OTHER_ENTITY ( ID IDENTITY PRIMARY KEY, CREATED DATE, ENTITY_WITH_STRINGY_BIG_DECIMAL INTEGER);
CREATE TABLE ENTITY_WITH_DIRECTIONS ( ID IDENTITY PRIMARY KEY, DIRECTIONS INTEGER ARRAY);

Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
CREATE TABLE ENTITY_WITH_STRINGY_BIG_DECIMAL ( id SERIAL PRIMARY KEY, Stringy_number DECIMAL(20,10), DIRECTION INTEGER);
CREATE TABLE OTHER_ENTITY ( ID SERIAL PRIMARY KEY, CREATED DATE, ENTITY_WITH_STRINGY_BIG_DECIMAL INTEGER);
CREATE TABLE ENTITY_WITH_DIRECTIONS ( ID SERIAL PRIMARY KEY, DIRECTIONS INTEGER ARRAY);
4 changes: 2 additions & 2 deletions spring-data-r2dbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-data-r2dbc</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>

<name>Spring Data R2DBC</name>
<description>Spring Data module for R2DBC</description>
Expand All @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>
</parent>

<properties>
Expand Down
4 changes: 2 additions & 2 deletions spring-data-relational/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-data-relational</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>

<name>Spring Data Relational</name>
<description>Spring Data Relational support</description>

<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-relational-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.0.0-2078-custom-converter-in-collection-SNAPSHOT</version>
</parent>

<properties>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,7 @@
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.PersistentPropertyPathAccessor;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.CachingValueExpressionEvaluatorFactory;
import org.springframework.data.mapping.model.ConvertingPropertyAccessor;
import org.springframework.data.mapping.model.EntityInstantiator;
import org.springframework.data.mapping.model.ParameterValueProvider;
import org.springframework.data.mapping.model.PersistentEntityParameterValueProvider;
import org.springframework.data.mapping.model.PropertyValueProvider;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.mapping.model.SpELContext;
import org.springframework.data.mapping.model.ValueExpressionEvaluator;
import org.springframework.data.mapping.model.ValueExpressionParameterValueProvider;
import org.springframework.data.mapping.model.*;
import org.springframework.data.projection.EntityProjection;
import org.springframework.data.projection.EntityProjectionIntrospector;
import org.springframework.data.projection.EntityProjectionIntrospector.ProjectionPredicate;
Expand Down Expand Up @@ -790,14 +781,35 @@ private Object writeCollection(Iterable<?> value, TypeInformation<?> type) {
}

for (Object o : value) {
mapped.add(writeValue(o, component));
mapped.add(unwrap(writeValue(o, component)));
}

if (type.getType().isInstance(mapped) || !type.isCollectionLike()) {
return mapped;
}

return getConversionService().convert(mapped, type.getType());
// if we succeeded converting the members of the collection, we actually ignore the fallback targetType since that
// was derived without considering custom conversions.
Class<?> targetType = type.getType();
if (!mapped.isEmpty()) {

Class<?> targetComponentType = mapped.get(0).getClass();
targetType = Array.newInstance(targetComponentType, 0).getClass();
}
return getConversionService().convert(mapped, targetType);
}

/**
* Unwraps technology specific wrappers. Custom conversions may choose to return a wrapper class that contains additional information for the technology driver.
* These wrappers can't be used as members of a collection, therefore we may have to unwrap the values.
*
* This method allows technology specific implemenations to provide such an unwrapping mechanism.
*
* @param convertedValue a value that might need unwrapping.
*/
@Nullable
protected Object unwrap(@Nullable Object convertedValue) {
return convertedValue;
}

static Predicate<RelationalPersistentProperty> isConstructorArgument(PersistentEntity<?, ?> entity) {
Expand Down