复合标识符的任何部分都不能为空



我正在尝试进行复合主键映射,但不起作用。

必备条件是:

  • 关系可能与@IdClass注释
  • 我需要@ManyToOne与个人实体的关系

我的代码:

@Entity
@IdClass(PhonePK.class)
public class Phone implements Serializable{
    @Id
    @Column(name = "codigo", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long code;
    @Id
    @ManyToOne
    @JoinColumn(name = "person", referencedColumnName = "code", nullable = false)
    private Person person;
    @Basic
    @Column(name = "number", nullable = false)
    private Integer number;
    //getters and setters
    //equals and hashcode
}
public class PhonePK implements Serializable {
    private Long code;
    private Long person;
    public PhonePK(){}
    public PhonePK(Long code, Long person) {
        this.code = code;
        this.person = person;
    }
    //getters and setters
    //equals and hashcode
}
public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "code", nullable = false)
    private Long code;
    //getters and setters
    //equals and hashcode
}

他们的方式我试图坚持:

//a lot of code
//em = Entitymanager
em.persist(person);
phone.setPerson(person);
em.persist(phone);

我收到的错误是:

由以下原因引起:javax.persistence.PersistenceException: org.hibernate.HibernateException: 复合标识符的任何部分都不能为空

您在电话实体上设置的人员很可能还没有 ID 和 ID。坚持不保证和 ID。建议您同时刷新事务。

相关: 未在 persis() 上添加 ID

我在hibernate.atlassian中发现了一个问题。我放弃了复合键,只是将Person中的外键放在Phone中。

相关内容

最新更新