#2199 - ScalarTypeWrapper doesn't handle "nullValue" correctly

Fix for - standard JPA AttributeConverter which doesn't have the getNullValue method, he/she can't convert null to a custom null object

AttributeConverterAdapter probes the AttributeConverter for the nullValue rather than just assuming it is null.
This commit is contained in:
Robin Bygrave
2021-03-18 16:14:46 +13:00
parent 2e16f05a70
commit bb73c30bb7
2 changed files with 73 additions and 1 deletions
@@ -10,14 +10,24 @@ import javax.persistence.AttributeConverter;
class AttributeConverterAdapter<B,S> implements ScalarTypeConverter<B, S> {
private final AttributeConverter<B,S> converter;
private final B nullValue;
AttributeConverterAdapter(AttributeConverter<B, S> converter) {
this.converter = converter;
this.nullValue = probeNullValue();
}
private B probeNullValue() {
try {
return converter.convertToEntityAttribute(null);
} catch (Exception e) {
return null;
}
}
@Override
public B getNullValue() {
return null;
return nullValue;
}
@Override
@@ -0,0 +1,62 @@
package io.ebeaninternal.server.type;
import org.junit.Test;
import javax.persistence.AttributeConverter;
import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings({"rawtypes", "unchecked"})
public class ScalarTypeWrapperAdapterTest {
private final ScalarTypeString stringType = ScalarTypeString.INSTANCE;
private final MyAdapter myAdapter = new MyAdapter();
private final AttributeConverterAdapter converterAdapter = new AttributeConverterAdapter(myAdapter);
private final ScalarTypeWrapper<Long, String> wrapper = new ScalarTypeWrapper(Long.class, stringType, converterAdapter);
@Test
public void toJdbcType() {
assertThat(wrapper.toJdbcType(42L)).isEqualTo("L42");
assertThat(wrapper.toJdbcType(93L)).isEqualTo("L93");
}
@Test
public void toJdbcType_when_nullValue() {
assertThat(wrapper.toJdbcType(MyAdapter.NULL_VAL)).isNull();
}
@Test
public void toBeanType_when_null_expect_customNullValue() {
assertThat(wrapper.toBeanType(null)).isEqualTo(MyAdapter.NULL_VAL);
}
@Test
public void toBeanType() {
assertThat(wrapper.toBeanType("L34")).isEqualTo(34L);
}
/**
* An AttributeConverter with a custom null value (of -1L).
*/
private static class MyAdapter implements AttributeConverter<Long, String> {
private static final Long NULL_VAL = -1L;
@Override
public String convertToDatabaseColumn(Long val) {
if (val == null || val.equals(NULL_VAL)) {
return null;
}
return "L" + val;
}
@Override
public Long convertToEntityAttribute(String dbData) {
if (dbData == null) {
return NULL_VAL;
}
return Long.parseLong(dbData.substring(1));
}
}
}