Bart van Heukelom
Bart van Heukelom

Reputation: 44114

Map Map<Entity, Enum> in JPA 2

@Entity
public class Company {

    public enum CompanyMemberLevel {
        MEMBER, GAME_ADMIN, COMPANY_ADMIN
    }

    ...

    private Map<User, CompanyMemberLevel> members = new HashMap<User, CompanyMemberLevel>();

members is a collection of Users (another entity class) that are part of a company, and CompanyMemberLevel an enum that specifies what permissions they have in that company (should be saved as string).

How should I annotate members to achieve what I want? I can only find examples about Map<Basic, Entity>, not the other way around. Or is this map the wrong structure here?

(Also, could I get even more freaky and map Map<Entity, Set<Enum>>?

Upvotes: 1

Views: 670

Answers (2)

But this for Hibernate 5.4 Try this

    @ElementCollection
    @CollectionTable(name = "members")
    @Column(name = "role")
    @Enumerated(EnumType.STRING)
    private Map<User, CompanyMemberLevel> members;

describe in here

Upvotes: 0

BobG
BobG

Reputation: 2171

To answer the question specifically:

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-indexed

Specifically, see section 7.2.2.2, and:

"@MapKeyJoinColumn/@MapKeyJoinColumns if the map key type is another entity."

However, if I had to model the objects you're trying to model, I'd rather do it like so:

class Company {
    @OneToMany private Set<User> users;
    ...
}

class User {
    @ElementCollection Set<CompanyMemberLevel> memberLevels;
    ...
}

because semantically it makes a lot more sense.

Upvotes: 2

Related Questions