2

我正在尝试在 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

我究竟做错了什么?

4

1 回答 1

0

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

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

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

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

正如第一篇文章所建议的那样,使用 @MapsId 会让休眠知道子实体将共享父实体的 id。所以我把我的课程改成:

@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
    ...

然后问题来自 Hibernate 使用 GenerationType.Auto 如第三篇文章中所建议的那样。因此,为了指示 Hibernate 生成 UUID,我按照第二篇文章中的示例将 Profile id 更改为如下所示:

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

...

它就像一个魅力。我希望它会帮助其他人在未来面临同样的问题

于 2020-11-04T14:25:34.493 回答