gpt4 book ai didi

java - Hibernate OneToOne 试图从 null 一对一属性分配 id

转载 作者:行者123 更新时间:2023-12-05 04:56:57 28 4
gpt4 key购买 nike

我正在尝试在 2 个实体之间创建一对一关系,其中“子”被“父”ID 引用为外键。这是我的 2 个实体:

@Entity
@Table(name = "users")
public class User extends PanacheEntityBase implements Serializable {

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
String id;

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL , optional = false)
Profile profile;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public Profile getProfile() {
return profile;
}

public void setProfile(Profile profile) {
this.profile = profile;
}
}

@Entity
@Table(name = "profiles")
public class Profile extends PanacheEntityBase implements Serializable {

@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "user_id")
String id;

@OneToOne
@MapsId
@JoinColumn(name = "user_id")
User user;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}

在保存时,我构建对象并将其持久化:

    User user = new User();
Profile profile = new Profile();
user.setProfile(profile);
userRepository.persist(user);

但是我得到了这个错误

org.jboss.resteasy.spi.UnhandledException: javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null 一对一属性 [com.myne.entities.Profile.user]

我做错了什么?

最佳答案

经过更多的研究,我终于能够解决这个问题。我在这 3 个帖子之间使用了混合体

https://howtodoinjava.com/hibernate/hibernate-one-to-one-mapping/

https://stackoverflow.com/a/52010963/3353167

https://stackoverflow.com/a/18622821/3353167

正如第一篇文章所建议的那样,使用@MapsId 会让 hibernate 知道子实体将共享父实体的 ID。所以我将类(class)更改为:

@Entity
@Table(name = "users")
public class User extends PanacheEntityBase implements Serializable {

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
String id;

@OneToOne
@MapsId
Profile profile;

...

@Entity
@Table(name = "profiles")
public class Profile extends PanacheEntityBase implements Serializable {

@Id
@Column(name = "user_id")
String id;

// removed the User Column
...

然后问题来自使用 GenerationType.Auto 的 Hibernate,如第三篇文章中所建议的。因此,为了指示 Hibernate 生成一个 UUID,我遵循了第二篇文章中的示例并将配置文件 ID 更改为如下所示:

@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "user_id", updatable = false, nullable = false)
@Id
String id;

...

它就像一个魅力。我希望它能帮助将来遇到同样问题的其他人

关于java - Hibernate OneToOne 试图从 null 一对一属性分配 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64678779/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com