Persisting set of Enums in a many-to-many unidirectional mapping
Simple use below mapping on your entity. Suppose that we have:
public enum TestEnum { A, B }
Then in your Entity class:
@ElementCollection(targetClass = TestEnum.class)
@CollectionTable(
name = "yourJoinTable",
joinColumns = @JoinColumn(name = "YourEntityId")
)
@Column(name = "EnumId")
private final Set<TestEnum> enumSet= new HashSet<>();
You should decide whether your Platform
is an entity or not.
If it's an entity, it can't be an enum
, because list of possible platforms is stored in the database, not in the application. It should be a regular class with @Entity
annotation and you will have a normal many-to-many relation.
If it isn't an entity, then you don't need TBL_PLATFORM
table, and you don't have a many-to-many relation. In this case you can represent a set of Platform
s either as an integer field with bit flags, or as a simple one-to-many relation. JPA 2.0 makes the latter case simple with @ElementCollection
:
@ElementCollection(targetClass = Platform.class)
@CollectionTable(name = "TBL_APP_PLATFORM",
joinColumns = @JoinColumn(name = "APP_ID"))
@Column(name = "PLATFORM_ID")
protected Set<Platform> _platforms;
-
create table TBL_APP_PLATFORM (
APP_ID bigint not null,
PLATFORM_ID bigint not null, -- the ordinal number of enum value
primary key (APP_ID, PLATFORM_ID)
);
and enum Platform
without annotations.