如何正确映射pojo中的Set for hibernate?

时间:2016-03-06 18:59:42

标签: java spring hibernate spring-mvc mapping

我需要在我的应用程序上对用户进行身份验证,但是我在User类的@ElementCollection映射上遇到了一些困难。

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

用户类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

UserProfile类为:

    @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类无法读取。

编辑 - 插入@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);

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

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

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

我在这里缺少什么?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为你必须保持&#34;多对多&#34;仅映射&#34; UserProfile&#34; class,因为&#34; ElementCollection&#34;用于连接不是实体的元素,在您的情况下,您必须使用&#34; CollectionTable&#34;注释

@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);

&#34; CollectionTable&#34;注释表示集合的名称和连接列,之后,&#34; AttributesOverrides&#34;注释设置了作为集合一部分的列,在这种情况下,我只是将&#34; Type&#34;列,但您可以添加更多。

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

我希望这些信息可以帮到你。

祝你好运。