It is a copy of the DB table definition as it is, and since it was covered with reserved words and definitions, it was defined with _
.
Problematic enum
public enum Moge {
hoge("hoge"), fuga("fuga"), _native("native"); //native is a reserved word
/*abridgement*/
Here, the query result to Jdbc
was mapped using ʻEnum.valueOf, but the value that can be obtained from the DB is
native, which is different from
_native`, so it could not be mapped.
I made an annotation that conveys the field corresponding to the value that can be taken from the DB, and made it possible to map by processing the annotation with reflection.
MapByValue
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MapByValue {
String value();
}
Annotation
public enum Moge {
hoge("hoge"), fuga("fuga"),
@MapByValue(value = "native") _native("native"); //native is a reserved word
/*Omitted below*/
How to process annotations
@SuppressWarnings("unchecked")
private Object mapEnum(Class<?> clz, String columnValue) {
/*abridgement*/
String finalColumnValue = columnValue;
columnValue = Arrays.stream(clz.getFields()) //Get all fields
.filter(it -> {
//When MapByValue annotation is attached and its value is equal to colmunValue
MapByValue mapByValue = it.getAnnotation(MapByValue.class);
return mapByValue != null && mapByValue.value().equals(finalColumnValue);
})
.findFirst()
.map(Field::getName) //Use the name of the given field
.orElse(finalColumnValue);
return clz.cast(Enum.valueOf((Class<Enum>) clz, columnValue));
}
@SuppressWarnings("rawtypes")
@Override
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
Class<?> clz = pd.getPropertyType(); //Get type information
/*abridgement*/
if (clz.isEnum()) { //For enum
byte[] bytes = rs.getBytes(index);
if (isEmpty(bytes)) {
return null;
}
return mapEnum(clz, new String(bytes, Charset.forName("UTF-8")));
}
/*abridgement*/
Since all ʻenum had a function to convert from value to ʻenum
for the convenience of converting from Json, I thought about using this from reflection, but it is more versatile to process with annotations. I decided.
I wish I could do valueOf
ʻOverride` ...