Is there a way in JPA to map a collection of Enums within the Entity class? Or the only solution is to wrap Enum with another domain class and use it to map the collection?<
I'm using a slight modification of java.util.RegularEnumSet to have a persistent EnumSet:
@MappedSuperclass
@Access(AccessType.FIELD)
public class PersistentEnumSet>
extends AbstractSet {
private long elements;
@Transient
private final Class elementType;
@Transient
private final E[] universe;
public PersistentEnumSet(final Class elementType) {
this.elementType = elementType;
try {
this.universe = (E[]) elementType.getMethod("values").invoke(null);
} catch (final ReflectiveOperationException e) {
throw new IllegalArgumentException("Not an enum type: " + elementType, e);
}
if (this.universe.length > 64) {
throw new IllegalArgumentException("More than 64 enum elements are not allowed");
}
}
// Copy everything else from java.util.RegularEnumSet
// ...
}
This class is now the base for all of my enum sets:
@Embeddable
public class InterestsSet extends PersistentEnumSet {
public InterestsSet() {
super(InterestsEnum.class);
}
}
And that set I can use in my entity:
@Entity
public class MyEntity {
// ...
@Embedded
@AttributeOverride(name="elements", column=@Column(name="interests"))
private InterestsSet interests = new InterestsSet();
}
Advantages:
java.util.EnumSet
for a description)Drawbacks:
RegularEnumSet
and PersistentEnumSet
are nearly the same)
EnumSet.noneOf(enumType)
in your PersistenEnumSet
, declare AccessType.PROPERTY
and provide two access methods which use reflection to read and write the elements
field@Embeddable
to PersistentEnumSet
and drop the
extra class (... interests = new PersistentEnumSet<>(InterestsEnum.class);
)@AttributeOverride
, as given in my example, if you've got more than one PersistentEnumSet
in your entity (otherwise both would be stored to the same column "elements")values()
with reflection in the constructor is not optimal (especially when looking at the performance), but the two other options have their drawbacks as well:
EnumSet.getUniverse()
makes use of a sun.misc
class