有人可以告诉我我在做什么错吗?我有以下表格:

java - org.hibernate.exception.ConstraintViolationException:列'pacientId'不能为null-LMLPHP

和实体:

@Entity
@NamedQuery(name = "Pacients.findAll", query = "SELECT p FROM Pacients p")
public class Pacients implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int pacientId;

    private String name;

    private String surname;

    // bi-directional many-to-one association to DetaliiPacient
    @OneToOne(mappedBy = "pacient")
    @Cascade(value = { CascadeType.ALL})
    private PacientsDetails pacientDetail;

}

@Entity
@Table
@NamedQuery(name = "PacientsDetails.findAll", query = "SELECT d FROM PacientsDetails d")
public class PacientsDetails implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int pacientDetailsId;

    private String address;

    @OneToOne
    @JoinColumn(name = "pacientId",referencedColumnName="pacientId")
    @Cascade(value = { CascadeType.ALL})
    @JsonBackReference
    private Pacients pacient;
}


“ pacients”表中的“ pacientId”字段为AUTO_INCREMENT,我正在使用mysql数据库。

我在执行操作时出现标题错误:

sessionFactory.getCurrentSession().persist(pacient);


在日志中,我看到了Hibernate在这样做:

Hibernate: insert into Pacients (doctorId, name, surname) values (?, ?, ?)
Hibernate: insert into PacientsDetails (address, pacientId) values (?, ?)


但是问题在于,在第二个查询中,无法识别pacientId的值(这是第一个查询生成的全新值)。

有人可以告诉我我所缺少的吗?
先感谢您!

最佳答案

我假设您正在像这样创建自己的实体(我知道这些字段是私有的,但是我们假装它们不是)

pacient = new Pacients();
// set name & surname
pacient.pacientDetail = new PacientsDetails();
// set address


如果是这种情况,您还需要在pacientsDetails中设置pacients字段,因为根据您的appedBy,PacientsDetails正在映射关系

@OneToOne(mappedBy = "pacient")


所以应该看起来像这样

pacient = new Pacients();
// set name & surname
pacient.pacientDetail = new PacientsDetails();
// set address
pacient.pacientDetail.pacient = pacient;

09-19 14:44