Registering Converters in JPA 2.1 with EclipseLink

前端 未结 4 1752
醉酒成梦
醉酒成梦 2021-02-06 16:00

On JavaEE environment, I use JPA 2.1 implementation with EclipseLink,

I have some entities that contain enums. So I have created converters for these enume

4条回答
  •  有刺的猬
    2021-02-06 16:59

    Wait till they release the patch for your application server.

    https://bugs.eclipse.org/bugs/show_bug.cgi?id=443546

    The release schedules pending are listed in http://www-01.ibm.com/support/docview.wss?uid=swg27004980

    The workaround for now is to store it as a String and have a getter and setter that would do the transform for you like this

    public final class StaticEnumToStringConverter {
    
        public static > String convertToDatabaseColumn(final E attribute) {
    
            if (attribute == null) {
                return null;
            }
            return attribute.toString();
        }
    
        public static > E convertToEntityAttribute(final String dbData, final Class enumClass) {
    
            if (dbData == null) {
                return null;
            }
            for (final E c : EnumSet.allOf(enumClass)) {
                if (dbData.equals(c.toString())) {
                    return c;
                }
            }
            throw new IllegalArgumentException(dbData);
    
        }
    
        private StaticEnumToStringConverter() {
    
        }
    }
    

    Then use in the JPA Entity as:

    @NotNull
    @Column(nullable = false)
    private String genderAtBirth;
    
    public Gender getGenderAtBirth() {
        return StaticEnumToStringConverter.convertToEntityAttribute(genderAtBirth, Gender.class);
    }
    public void setGenderAtBirth(final Gender genderAtBirth) {
    
        this.genderAtBirth = StaticEnumToStringConverter.convertToDatabaseColumn(genderAtBirth);
    }
    

提交回复
热议问题