Is it possible to write a generic enum converter for JPA?

后端 未结 4 1741
萌比男神i
萌比男神i 2020-12-01 04:51

I wanted to write a Converter for JPA that stores any enum as UPPERCASE. Some enums we encounter do not follow yet the convention to use only Uppercase letters so until they

4条回答
  •  臣服心动
    2020-12-01 05:07

    What you need to do is write a generic base class and then extend that for each enum type you want to persist. Then use the extended type in the @Converter annotation:

    public abstract class GenericEnumUppercaseConverter> implements AttributeConverter {
        ...
    }
    
    public FooConverter
        extends GenericEnumUppercaseConverter 
        implements AttributeConverter // See Bug HHH-8854
    {
        public FooConverter() {
            super(Foo.class);
        }
    }
    

    where Foo is the enum you want to handle.

    The alternative would be to define a custom annotation, patch the JPA provider to recognize this annotation. That way, you could examine the field type as you build the mapping information and feed the necessary enum type into a purely generic converter.

    Related:

    • https://hibernate.atlassian.net/browse/HHH-8854

提交回复
热议问题