如何使用休眠在 POJO 上正确映射 Set<Entity>?

how to correctly map a Set<Entity> on a POJO using hibernate?

我正在尝试将 User class 绑定到 Set 来存储每个用户的配置文件。我摆弄了一下,现在有点迷路了。我的Userclass的集合部分目前定义为:

@ElementCollection(targetClass = UserProfile.class)
@JoinTable(name = "HRM_USER_USER_PROFILE", 
        joinColumns = { @JoinColumn(name = "id_user") },
        inverseJoinColumns = { @JoinColumn(name = "id_profile") })
@Column(name = "id_profile")
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<String> userProfiles = new HashSet<String>(0);

我知道我在 Set 中使用了不同的类型。那是因为 UserProfile 被定义为:

@Entity
@Table(name="HRM_USER_PROFILE")
public class UserProfile extends BasePojo {

    @Enumerated(EnumType.STRING)
    @Column(name="type", length=15, unique=true, nullable=false)
    private UserProfileType type;

    public UserProfileType getType() {
        return type;
    }

    public void setType(UserProfileType type) {
        this.type = type;
    }

其中 UserProfileType 是声明为的枚举:

public enum UserProfileType {

    USER("USER"),
    DBA("DBA"),
    ADMIN("ADMIN");

    String userProfileType;

    private UserProfileType(String userProfileType){
        this.userProfileType = userProfileType;
    }

    public String getUserProfileType(){
        return userProfileType;
    }

我知道这与注释@ElementCollection有关。但是我很困惑。

我哪里错了?提前致谢!

Try this >>>

@Enumerated(EnumType.STRING) //enum type mapping with String Values
@Column(name="type", length=15, unique=true, nullable=false)
private UserProfileType type;

如果类型是数值

,您也可以使用 ordinal
@Enumerated(EnumType.ORDINAL) //enum type mapping with ordinal Values
@Column(name="type", length=15, unique=true, nullable=false)
private UserProfileType type;