diff --git a/ebean-core/src/main/java/io/ebeaninternal/server/type/AttributeConverterAdapter.java b/ebean-core/src/main/java/io/ebeaninternal/server/type/AttributeConverterAdapter.java index d72dd6f9c..e358dd891 100644 --- a/ebean-core/src/main/java/io/ebeaninternal/server/type/AttributeConverterAdapter.java +++ b/ebean-core/src/main/java/io/ebeaninternal/server/type/AttributeConverterAdapter.java @@ -10,14 +10,24 @@ import javax.persistence.AttributeConverter; class AttributeConverterAdapter implements ScalarTypeConverter { private final AttributeConverter converter; + private final B nullValue; AttributeConverterAdapter(AttributeConverter 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 diff --git a/ebean-core/src/test/java/io/ebeaninternal/server/type/ScalarTypeWrapperAdapterTest.java b/ebean-core/src/test/java/io/ebeaninternal/server/type/ScalarTypeWrapperAdapterTest.java new file mode 100644 index 000000000..1f79db003 --- /dev/null +++ b/ebean-core/src/test/java/io/ebeaninternal/server/type/ScalarTypeWrapperAdapterTest.java @@ -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 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 { + + 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)); + } + } +}