spring-data-relational
spring-data-relational copied to clipboard
generic enum converter dont work [DATAJDBC-566]
edwil13x opened DATAJDBC-566 and commented
i want to use a genric converter for all the enums i used in my project. but i got an error.
Explanations :
Given this enum
public enum Gender {
MALE("male"), FEMALE("female"), NON_BINARY("non-binary");
private String gender;
Gender(String gender) {
this.gender = gender;
}
public String toString() {
return gender;
}
}
and this jdbcConfig
@Configuration
public class DataJdbcConfiguration extends AbstractJdbcConfiguration {
public <T extends Enum<T>> Converter<String, T> createEnumReadingConverter(Class<T> enumClass) { return new Converter<String, T>() { @Override public T convert(String value) { for(T constant : enumClass.getEnumConstants()) { if(constant.toString().equalsIgnoreCase(value)) return constant; } throw new IllegalArgumentException("Unable to find Enum type for : " + value); } } ; }
@Override
public JdbcCustomConversions jdbcCustomConversions() {
Converter<String, Gender> genericGenderConverter = createEnumReadingConverter(Gender.class);
return new JdbcCustomConversions(Arrays.asList(genericGenderConverter));
}
}
=> why my genericGenderConverter is not use at all, and spring data back to the default enum converter.
Affects: 2.0.1 (Neumann SR1)
1 votes, 2 watchers
Jawad Ahmad commented
Same issue, and it still persists in latest versions as well. I am trying to register a specific enum converter but looks like bean overriding is disabled for Spring Data JDBC Auto Configuration
i have similar issue, try to use JdbcCustomConversions
to implement a function like Mybatis enumOrdinalTypeHandler
but doesn't work
Hi Guys I make it work like this enumOrdinalConverter
but while use enum type as query condition, it does't work, it use JdbcValue as input string and doesn't use converter
Hi Guys I make it work like this enumOrdinalConverter
but while use enum type as query condition, it does't work, it use JdbcValue as input string and doesn't use converter
@Ikki-Dai Thanks for the example code. I just tried it out (using 2.3.0) and it seems to work to me. It was able to read and write enums as integers in both generated queries (eg findAllByX) and custom annotated queries. Can you be more specific about where you saw the conversion failing?
@pwinckles I was tried on H2db with unit test. it seems convert between enum with jdbcValue directly. I can't remember more details, but you can tried again with h2db.
Yes, I was running against H2 as well. As far as I can tell, your solution works.
I still hope to have an option to determine enum write/read as string or ordinary in framework, after that it's no need to custom and register so many enum type converters