使用@EmbeddedId和@MapsId会导致插入NULL(不违反NULL约束) [英] Use of @EmbeddedId and @MapsId causes NULL inserted (NOT NULL constraint violation)

查看:61
本文介绍了使用@EmbeddedId和@MapsId会导致插入NULL(不违反NULL约束)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码

@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字段中.

When trying to persist or merge the Employee Entity, we can see that a NULL as attempted to be inserted into the company_id field.

如何避免插入 NULL ?

推荐答案

即使进行了连接,在创建新对象(不是从持久性上下文中获取)时, company 字段也将保留为.

Even with the wiring, when creating a new object (not fetched from the persistence context), the company field will remain null.

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

When Creating a new Employee entity, you will need to assure that you also initialize the company attribute:

@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;
    }
}

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

The Company entity you might acquire from the persistence context using a find. You also can create it from scratch using it's constructor.

这篇关于使用@EmbeddedId和@MapsId会导致插入NULL(不违反NULL约束)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆