【问题标题】:how to correctly map a Set in a pojo for hibernate?如何正确映射 pojo 中的 Set 以进行休眠?
【发布时间】:2016-06-20 06:13:21
【问题描述】:

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

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

User 类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、用户及其关系的 SQL 脚本,而是使用 @PostConstruct bean 在应用程序启动时加载默认值。

我希望打印出完整的用户信息,但我没有得到有关用户配置文件的信息。

我在这里错过了什么?

提前致谢!

【问题讨论】:

  • 发布的代码中没有一个 ElementCollection。你在做什么,你期望会发生什么,会发生什么? “我遇到了一些困难”不足以描述您的具体问题。
  • 抱歉,我忘记发布@ElementCollection 部分...现在正在编辑。
  • 为什么您认为必须将 ElementCollection 添加到此映射?你读过它的javadoc吗?你了解它的用途吗?你想达到什么目的?
  • 好的,我想我可能读错了一些东西。而且,我想要实现的是给定用户拥有的所有用户配置文件的映射。

标签: java spring hibernate spring-mvc mapping


【解决方案1】:

我认为您必须仅在“UserProfile”类上保留“多对多”映射,因为“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”注解设置属于您的集合的列,在这种情况下,我只是放了“类型”列,但是您可以添加更多。

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

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

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多