使用@EmbeddedId和@MapsId会导致插入NULL(违反NOT NULL约束)

时间:2017-07-21 19:03:00

标签: java jpa

使用以下代码

@Embeddable
public class EmployeeId implements Serializable {
    @Column(name = "company_id")
    private Long companyId;

    @Column(name = "employee_id")
    private Long employeeNumber;
}

@Entity
public class Employee {
    @EmbeddedId
    private EmployeeId id;

    private String name;

    @MapsId("name=companyId")
    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

尝试保留或合并Employee实体时,我们可以看到尝试将NULL插入到company_id字段中。

如何避免插入NULL

1 个答案:

答案 0 :(得分:1)

即使使用布线,在创建新对象(未从持久性上下文中提取)时,company字段仍将为null

创建新的Employee实体时,您需要确保初始化company属性:

@Entity
public class Employee {
    @EmbeddedId
    private EmployeeId id;

    private String name;

    @MapsId("name=companyId")
    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;

    public Employee() {}

    public Employee(int id,String name,Company company) {
      this.name = name;
      this.id = new EmployeeId(id,company.id);
      this.company = company;
    }
}

您可以使用Company从持久性上下文中获取的find实体。您也可以使用它的构造函数从头开始创建它。