1

I have an entity with an element of type enum:

@Column(name = "COL_NAME")
@Convert(converter = EnumConverter.class)
private COLNAME colname;

I need a generic converter (I don't want to write one new converter for each enum I'll have in my entities)

import java.lang.reflect.*;

@Converter(autoApply = false)
public class EnumConverter implements AttributeConverter<Object, String>{

@Override
public String convertToDatabaseColumn(Object attribute) {
String valuetoconvert = attribute.toString();
//do something on valuetoconvert
return valueconverted;
}

@Override
public Object convertToEntityAttribute(String dbData) {
// Object to return with dbData read from DB and modified
return objectconverted
}

}

In convertToEntityAttribute I try with Enumeration.valueOf, but this method need the class of enum. How can I try to find this?... if this is the correct way to do so. Thanks

P.S. I find, googling, some approach tending to minimize the code written, but in every case I must write one class for each enum. And I don't want this. Is it possible?

Giant2
  • 461
  • 1
  • 4
  • 15

1 Answers1

1

So, in essence, you're asking how to inject the type of the annotated property into the AttributeConverter. I'm afraid that's impossible with vanilla JPA.

If you're using Hibernate, you could use a composite user type instead. See here, specifically section 4.4. 'Type Parameterization'. You'd end up with something like:

@Type(type = "com.example.ConvertibleEnumType", parameters = @Parameter(name = "lookup", value = MyEnum.class))
private MyEnumClass property;

and you'd still have to rely on reflection inside your custom ConvertibleEnumType definition heavily, but it would work - you would be able to read the value of lookup inside setParameterValues.

(TBH personally, I'd still consider a separate converter per each enum, using e.g. the approach described here, to be the cleaner solution)

crizzis
  • 9,978
  • 2
  • 28
  • 47