Persisting set of Enums in a many-to-many unidirectional mapping

后端 未结 2 1764
北荒
北荒 2020-12-07 19:16

I\'m using Hibernate 3.5.2-FINAL with annotations to specify my persistence mappings. I\'m struggling with modelling a relationship between an Application and a set of Platf

相关标签:
2条回答
  • 2020-12-07 19:58

    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<>();
    
    0 讨论(0)
  • 2020-12-07 20:10

    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 Platforms 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.

    0 讨论(0)
提交回复
热议问题