我正在尝试在 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: 试图从空的一对一属性 [com.myne.entities.Profile.user] 分配 id
我究竟做错了什么?