| There is an issue when configuring a converter to convert a collection into a single field. I have tried as many solutions as I can before submitting this issue and searched the forums for an example that does something similar but to no avail. I simply cant find a way of not getting this error when The error I receive is as follows:
The field is annotated as follows:
@Valid
@Convert(converter = ConverterListToString.class)
@Column(columnDefinition = "text")
private List<Long> bookingIds = new ArrayList<>();
The converter code is as follows:
@Converter
public class ConverterListToString
extends org.hibernate.type.descriptor.java.AbstractTypeDescriptor<List>
implements AttributeConverter<List, String> {
public static final ConverterListToString INSTANCE = new ConverterListToString();
private static final long serialVersionUID = -4794345758375860474L;
public ConverterListToString() {
super(List.class);
}
@Override
public String convertToDatabaseColumn(List attribute) {
if (CollectionUtils.isNotEmpty(attribute) && attribute.stream().allMatch(instance -> instance instanceof Long))
return StringUtils.join(attribute, ",");
return GeneralUtils.serializeObjectToString(attribute);
}
@Override
public List convertToEntityAttribute(String dbData) {
if (StringUtils.isEmpty(dbData))
return new ArrayList();
if (Pattern.compile("[0-9,]*").matcher(dbData).matches()) {
try (Stream<String> stream = Stream.of(dbData.split(","))) {
return stream.map(Long::parseLong).collect(Collectors.toList());
}
}
return GeneralUtils.deserializeObjectFromString(List.class, dbData, new ArrayList<>());
}
@Override
public Class<List> getJavaTypeClass() {
return List.class;
}
@Override
public List fromString(String value) {
return convertToEntityAttribute(value);
}
@Override
public String toString(List value) {
return convertToDatabaseColumn(value);
}
@Override
public <X> List wrap(X value, WrapperOptions options) {
if ( value == null ) {
return null;
}
if ( String.class.isInstance( value ) ) {
return convertToEntityAttribute((String)value);
}
throw unknownWrap( value.getClass() );
}
@Override
public <X> X unwrap(List value, Class<X> type, WrapperOptions options) {
if ( value == null ) {
return null;
}
if ( String.class.isAssignableFrom( type ) ) {
return (X) convertToDatabaseColumn(value);
}
throw unknownUnwrap( type );
}
@Override
public String extractLoggableRepresentation(List value) {
return convertToDatabaseColumn(value);
}
@Override
public int extractHashCode(List value) {
return value.hashCode();
}
}
I am happy to provide more information if required. The error is in the logs, it does not appear to make any material difference to the way the code operates. It may well be that I have configured the annotations incorrectly but if that is the case it is not obvious what the annotations should be and the combinations I have tried either didn't work or made no difference. |