Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of @EmbeddedId and @MapsId causes NULL inserted (NOT NULL constraint violation)

Tags:

java

jpa

With using following code

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

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.

How can I avoid a NULL to be inserted?

like image 882
YoYo Avatar asked Oct 15 '25 14:10

YoYo


1 Answers

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

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

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

like image 113
YoYo Avatar answered Oct 18 '25 03:10

YoYo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!