首页 > 解决方案 > EclipseLink 是否有类似 Hibernate Interceptors 的功能?

问题描述

找到了一种在 JPA 中使用 Hibernate 拦截器将枚举用作具有自己表的实体的方法。例如,我想用作枚举后面的实体:

@Entity
public enum Color {

    RED(255, 0, 0),
    GREEN(0, 255, 0),
    BLUE(0, 0, 255)

    @Id
    public final byte id = (byte)ordinal();

    @Column(unique = true, nullable = false)
    public final String name = name();

    @Column(nullable = false)
    public final int red;

    @Column(nullable = false)
    public final int green;

    @Column(nullable = false)
    public final int blue;

}

为了使 JPA 正确地与该实体一起工作,我们可以编写以下拦截器,它将枚举转换为它的序号以保存在数据库中:

public class EnumAsEntityInterceptor extends EmptyInterceptor {

    @Override
    public Object instantiate(String entityName, EntityMode entityMode, Serializable id) {
        try {
            Object o;
            Class cls = Class.forName(entityName);
            if (cls.isEnum() && id instanceof Number) {
                o = cls.getEnumConstants()[((Number)id).intValue()];
            } else {
                o = super.getEntity(entityName, id);
            }
            return o;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

启用此拦截器后,我们可以使用枚举实体:

entityManager.merge(Color.RED);

但是这个解决方案只适用于 Hibernate。有没有办法用 EclipseLink 做类似的事情?经过一番研究,我没有发现 EclipseLink 中有任何功能可以做到这一点。

标签: javahibernatejpajakarta-eeeclipselink

解决方案


推荐阅读