如何正确映射 pojo 中的 Set 以进行休眠?

how to correctly map a Set in a pojo for hibernate?

我需要在我的应用程序上对用户进行身份验证,但我在用户 class.

上的 @ElementCollection 映射遇到了一些困难

我正在使用在 this Spring Security tutorial 上找到的示例来构建我的应用程序,因此这里显示的大部分内容都与那个非常相似。

用户 class Set<UserProfile> 最初定义为:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "HRM_USER_USER_PROFILE", 
     joinColumns = { @JoinColumn(name = "USER_ID") }, 
     inverseJoinColumns = { @JoinColumn(name = "USER_PROFILE_ID") })
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
// -- getter and setter

UserProfileclass为:

    @Column(name="type", length=15, unique=true, nullable=false)
    private String type = UserProfileType.USER.getUserProfileType();

    public String getType() {
        return type;
    }

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

UserProfileType 枚举为:

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

String userProfileType;

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

public String getUserProfileType(){
    return userProfileType;
}

已经保存在数据库中,但是 User class 无法读取。

编辑 - 插入 @ElementCollection 部分

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

我注意到用户 table 上的 user_profiles 列未创建,也未创建可能引用此映射的任何其他 table。

我使用 @PostConstruct bean 在应用程序启动时加载默认值,而不是 运行 SQL 脚本加载 UserProfileType、用户及其关系。

我希望打印出完整的用户信息,但我没有得到有关用户个人资料的信息。

我在这里错过了什么?

提前致谢!

我认为您必须仅在 "UserProfile" class 上保留 "Many-to-Many" 映射,因为 "ElementCollection" 用于连接不是实体的元素,在您的情况下,您必须使用 "CollectionTable" 注释。

@ElementCollection
@CollectionTable(name="HRM_USER_USER_PROFILE", joinColumns=@JoinColumn(name="id_profile"))
@AttributeOverrides({
          @AttributeOverride(name="type", 
                             column=@Column(name="TYPE"))
        })
private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);

"CollectionTable" 注释指示您的集合的名称和连接列,之后,"AttributesOverrides" 注释设置属于您的集合的列,在这种情况下,我只是把 "Type" 列,但您可以添加更多。

... 
@AttributeOverrides({
    @AttributeOverride(name="type", column=@Column(name="TYPE")),
    @AttributeOverride(name="otherColumn", column=@Column(name="OTHER_COLUMN"))
})
...

希望这些信息对您有所帮助。

祝你好运。