Found a way to use an enum as the entity with its own table in JPA using Hibernate Interceptors. For example, I want to use as an entity following enum:
@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;
}
To make JPA correctly work with that entity, we can write the following Interceptor, that converts an enum to it's ordinal to save in database:
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);
}
}
}
After enabling this interceptor, we can work with the enum entity:
entityManager.merge(Color.RED);
But this solution works only with Hibernate. Is there a way to do similar with EclipseLink? After some research, I didn't found any functionality in EclipseLink to do that.