JPA map collection of Enums

后端 未结 6 696
滥情空心
滥情空心 2020-11-27 12:46

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?<

6条回答
  •  温柔的废话
    2020-11-27 13:26

    tl;dr A short solution would be the following:

    @ElementCollection(targetClass = InterestsEnum.class)
    @CollectionTable
    @Enumerated(EnumType.STRING)
    Collection interests;
    

    The long answer is that with this annotations JPA will create one table that will hold the list of InterestsEnum pointing to the main class identifier (Person.class in this case).

    @ElementCollections specify where JPA can find information about the Enum

    @CollectionTable create the table that hold relationship from Person to InterestsEnum

    @Enumerated(EnumType.STRING) tell JPA to persist the Enum as String, could be EnumType.ORDINAL

提交回复
热议问题