如何用休眠映射自定义枚举整数序数?

2022-09-03 13:06:49

我有一个名为 Status 的枚举类,如下所示

public enum Status {
    PENDING(0), SUCCESS(1), FAILED(-1);

    private int st;

    private Status(int st){
        this.st = st;
    }
}

从其他类中,我试图映射此状态枚举

public void setStatus(Status status) {
        this.status = status;
    }

    @Enumerated(EnumType.ORDINAL)
    public Status getStatus() {
        return status;
    }

当我运行此代码时,我得到

java.lang.IllegalArgumentException:枚举类数据的未知序号值。Status: -1 at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:93) at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:124) at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106) at

但我已经在枚举定义中有-1。


答案 1

您可以定义自己的定义,它定义了Hibernate应该如何映射这些枚举。UserType

请注意,序数定义了枚举值的索引,因此序数为 2。要使用枚举的属性映射枚举,您需要一个实现。FAILEDUserType

一些链接:


答案 2

这是一个使用字符串标签而不是int id的解决方案,但是它很容易适应。

public class User { 
    @Id
    private int id;

    @Type(type = "com.example.hibernate.LabeledEnumType")
    private Role role;
}


public enum Role implements LabeledEnum {
    ADMIN("admin"), USER("user"), ANONYMOUS("anon");

    private final String label;

    Role(String label) {
        this.label = label;
    }

    @Override
    public String getLabel() {
        return label;
    }
}


public interface LabeledEnum {
    String getLabel();
}


public final class LabeledEnumType implements DynamicParameterizedType, UserType {

    private Class<? extends Enum> enumClass;

    @Override
    public Object assemble(Serializable cached, Object owner)
            throws HibernateException {
        return cached;
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable) value;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        return x == y;
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        return x == null ? 0 : x.hashCode();
    }

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException {
        String label = rs.getString(names[0]);
        if (rs.wasNull()) {
            return null;
        }
        for (Enum value : returnedClass().getEnumConstants()) {
            if (value instanceof LabeledEnum) {
                LabeledEnum labeledEnum = (LabeledEnum) value;
                if (labeledEnum.getLabel().equals(label)) {
                    return value;
                }
            }
        }
        throw new IllegalStateException("Unknown " + returnedClass().getSimpleName() + " label");
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
            throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, Types.VARCHAR);
        } else {
            st.setString(index, ((LabeledEnum) value).getLabel());
        }
    }

    @Override
    public Object replace(Object original, Object target, Object owner)
            throws HibernateException {
        return original;
    }

    @Override
    public Class<? extends Enum> returnedClass() {
        return enumClass;
    }

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.VARCHAR};
    }

    @Override
    public void setParameterValues(Properties parameters) {
        ParameterType params = (ParameterType) parameters.get( PARAMETER_TYPE );
        enumClass = params.getReturnedClass();
    }
}