猿问

通用枚举 JPA AttributeConverter 实现

我试图解决的问题

我正在尝试为 Hibernate 实现枚举映射。到目前为止,我已经研究了可用的选项,并且@Enumerated(EnumType.ORDINAL)和似乎都@Enumerated(EnumType.STRING)不足以满足我的需求。这@Enumerated(EnumType.ORDINAL)似乎很容易出错,因为仅仅对枚举常量进行重新排序就会搞乱映射,而且这也@Enumerated(EnumType.STRING)不够,因为我使用的数据库已经充满了要映射的值,而这些值并不是什么我希望我的枚举常量被命名为(值是外语字符串/整数)。

目前,所有这些值都被映射到字符串/整数属性。同时,属性应该只允许有限的值集(想象一下meetingStatus属性允许字符串:PLANNEDCANCELEDDONE。或者另一个属性允许有限的整数值集:12345)。

我的想法是用枚举替换实现以提高代码的类型安全性。String / Integer 实现可能导致错误的一个很好的例子是表示此类值的 String 方法参数 - 使用 String 时,任何内容都会发生。另一方面,拥有 Enum 参数类型会引入编译时安全性。

到目前为止我最好的方法

似乎满足我需求的唯一解决方案是为每个枚举实现javax.persistence.AttributeConverter带有@Converter注释的自定义。由于我的模型需要相当多的枚举,因此为每个枚举编写自定义转换器很快就开始变得疯狂。因此,我寻找问题的通用解决方案 - >如何为任何类型的枚举编写通用转换器。以下答案在这里有很大帮助: https: //stackoverflow.com/a/23564597/7024402。答案中的代码示例提供了某种通用的实现,但对于每个枚举,仍然需要一个单独的转换器类。答案的作者还继续说道:

“另一种方法是定义一个自定义注释,修补 JPA 提供程序以识别该注释。这样,您可以在构建映射信息时检查字段类型,并将必要的枚举类型提供给纯通用转换器。”

这就是我认为我会感兴趣的。不幸的是,我找不到更多关于此的信息,并且我需要更多的指导来了解需要做什么以及它如何与这种方法一起工作。

目前的实施

public interface PersistableEnum<T> {

    T getValue();

}

public enum IntegerEnum implements PersistableEnum<Integer> {

    ONE(1),

    TWO(2),

    THREE(3),

    FOUR(4),

    FIVE(5),

    SIX(6);


    private int value;


    IntegerEnum(int value) {

        this.value = value;

    }


    @Override

    public Integer getValue() {

        return value;

    }

}

public abstract class PersistableEnumConverter<E extends PersistableEnum<T>, T> implements AttributeConverter<E, T> {


    private Class<E> enumType;


    public PersistableEnumConverter(Class<E> enumType) {

        this.enumType = enumType;

    }


    @Override

    public T convertToDatabaseColumn(E attribute) {

        return attribute.getValue();

    }


    @Override

    public E convertToEntityAttribute(T dbData) {

        for (E enumConstant : enumType.getEnumConstants()) {

            if (enumConstant.getValue().equals(dbData)) {

                return enumConstant;

            }

        }

        throw new EnumConversionException(enumType, dbData);

    }

}


这就是我能够实现部分通用转换器实现的方式。


目标:无需为每个枚举创建新的转换器类。


阿波罗的战车
浏览 195回答 3
3回答

Qyouu

幸运的是,您不应该为此修补休眠状态。您可以声明如下所示的注释:import java.lang.annotation.Retention;import java.lang.annotation.Target;import java.sql.Types;import static java.lang.annotation.ElementType.METHOD;import static java.lang.annotation.ElementType.FIELD;import static java.lang.annotation.RetentionPolicy.RUNTIME;@Target({METHOD, FIELD})&nbsp;@Retention(RUNTIME)public @interface EnumConverter{&nbsp; &nbsp;Class<? extends PersistableEnum<?>> enumClass() default IntegerEnum.class;&nbsp; &nbsp;int sqlType() default Types.INTEGER;}Hibernate 用户类型如下:import java.io.Serializable;import java.lang.annotation.Annotation;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Types;import java.util.Objects;import java.util.Properties;import org.hibernate.HibernateException;import org.hibernate.engine.spi.SharedSessionContractImplementor;import org.hibernate.usertype.DynamicParameterizedType;import org.hibernate.usertype.UserType;public class PersistableEnumType implements UserType, DynamicParameterizedType{&nbsp; &nbsp;private int sqlType;&nbsp; &nbsp;private Class<? extends PersistableEnum<?>> clazz;&nbsp; &nbsp;@Override&nbsp; &nbsp;public void setParameterValues(Properties parameters)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);&nbsp; &nbsp; &nbsp; EnumConverter converter = getEnumConverter(reader);&nbsp; &nbsp; &nbsp; sqlType = converter.sqlType();&nbsp; &nbsp; &nbsp; clazz = converter.enumClass();&nbsp; &nbsp;}&nbsp; &nbsp;private EnumConverter getEnumConverter(ParameterType reader)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; for (Annotation annotation : reader.getAnnotationsMethod()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (annotation instanceof EnumConverter) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (EnumConverter) annotation;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; throw new IllegalStateException("The PersistableEnumType should be used with @EnumConverter annotation.");&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public int[] sqlTypes()&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return new int[] {sqlType};&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Class<?> returnedClass()&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return clazz;&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public boolean equals(Object x, Object y) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return Objects.equals(x, y);&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public int hashCode(Object x) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return Objects.hashCode(x);&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Object nullSafeGet(ResultSet rs,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String[] names,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SharedSessionContractImplementor session,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Object owner) throws HibernateException, SQLException&nbsp;&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; Object val = null;&nbsp; &nbsp; &nbsp; if (sqlType == Types.INTEGER) val = rs.getInt(names[0]);&nbsp; &nbsp; &nbsp; if (sqlType == Types.VARCHAR) val = rs.getString(names[0]);&nbsp; &nbsp; &nbsp; if (rs.wasNull()) return null;&nbsp; &nbsp; &nbsp; for (PersistableEnum<?> pEnum : clazz.getEnumConstants())&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (Objects.equals(pEnum.getValue(), val)) return pEnum;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Can not convert " + val + " to enum " + clazz.getName());&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public void nullSafeSet(PreparedStatement st,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Object value,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int index,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SharedSessionContractImplementor session) throws HibernateException, SQLException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; if (value == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;st.setNull(index, sqlType);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;PersistableEnum<?> pEnum = (PersistableEnum<?>) value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (sqlType == Types.INTEGER) st.setInt(index, (Integer) pEnum.getValue());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (sqlType == Types.VARCHAR) st.setString(index, (String) pEnum.getValue());&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Object deepCopy(Object value) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public boolean isMutable()&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Serializable disassemble(Object value) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return Objects.toString(value);&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Object assemble(Serializable cached, Object owner) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return cached;&nbsp; &nbsp;}&nbsp; &nbsp;@Override&nbsp; &nbsp;public Object replace(Object original, Object target, Object owner) throws HibernateException&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; return original;&nbsp; &nbsp;}}然后,您可以使用它:import org.hibernate.annotations.Type;@Entity@Table(name="TST_DATA")public class TestData{&nbsp; &nbsp;...&nbsp; &nbsp;@EnumConverter(enumClass = IntegerEnum.class, sqlType = Types.INTEGER)&nbsp; &nbsp;@Type(type = "com.example.converter.PersistableEnumType")&nbsp; &nbsp;@Column(name="INT_VAL")&nbsp; &nbsp;public IntegerEnum getIntValue()&nbsp; &nbsp;...&nbsp; &nbsp;@EnumConverter(enumClass = StringEnum.class, sqlType = Types.VARCHAR)&nbsp; &nbsp;@Type(type = "com.example.converter.PersistableEnumType")&nbsp; &nbsp;@Column(name="STR_VAL")&nbsp; &nbsp;public StringEnum getStrValue()&nbsp; &nbsp;...}另请参阅Bauer、King、Gregory 撰写的优秀著作“Java Persistence with Hibernate”中的第5.3.3 章“Extending Hibernate with UserTypes ” 。

墨色风雨

我尝试了 1000 次创造相同的东西。动态为每个枚举生成转换器 - 没问题,但它们将具有相同的类。主要问题是:org.hibernate.boot.internal.MetadataBuilderImpl#applyAttributeConverter(java.lang.Class<? extends javax.persistence.AttributeConverter>, boolean)。如果转换器已经注册,我们会得到异常。public void addAttributeConverterInfo(AttributeConverterInfo info) {&nbsp; &nbsp; &nbsp; &nbsp; if ( this.attributeConverterInfoMap == null ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.attributeConverterInfoMap = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; final Object old = this.attributeConverterInfoMap.put( info.getConverterClass(), info );&nbsp; &nbsp; &nbsp; &nbsp; if ( old != null ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new AssertionFailure(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.format(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "AttributeConverter class [%s] registered multiple times",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; info.getConverterClass()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }也许我们可以更改org.hibernate.boot.internal.BootstrapContext Impl,但我确信它会创建过于复杂且不灵活的代码。

一只萌萌小番薯

简化:import com.pismo.apirest.mvc.enums.OperationType;import com.pismo.apirest.mvc.enums.support.PersistableEnum;import java.util.Objects;import java.util.Optional;import java.util.stream.Stream;import javax.persistence.AttributeConverter;import javax.persistence.Converter;import lombok.NonNull;import lombok.RequiredArgsConstructor;@SuppressWarnings("unused")public interface EnumsConverters {&nbsp; &nbsp; @RequiredArgsConstructor&nbsp; &nbsp; abstract class AbstractPersistableEnumConverter<E extends Enum<E> & PersistableEnum<I>, I> implements AttributeConverter<E, I> {&nbsp; &nbsp; &nbsp; &nbsp; private final E[] enumConstants;&nbsp; &nbsp; &nbsp; &nbsp; public AbstractPersistableEnumConverter(@NonNull Class<E> enumType) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; enumConstants = enumType.getEnumConstants();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public I convertToDatabaseColumn(E attribute) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Objects.isNull(attribute) ? null : attribute.getId();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public E convertToEntityAttribute(I dbData) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return fromId(dbData, enumConstants);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public E fromId(I idValue) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return fromId(idValue, enumConstants);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public static <E extends Enum<E> & PersistableEnum<I>, I> E fromId(I idValue, E[] enumConstants) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Objects.isNull(idValue) ? null : Stream.of(enumConstants)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(e -> e.getId().equals(idValue))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .findAny()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElseThrow(() -> new IllegalArgumentException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.format("Does not exist %s with ID: %s", enumConstants[0].getClass().getSimpleName(), idValue)));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; @Converter(autoApply = true)&nbsp; &nbsp; class OperationTypeConverter extends AbstractPersistableEnumConverter<OperationType, Integer> {&nbsp; &nbsp; &nbsp; &nbsp; public OperationTypeConverter() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super(OperationType.class);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答