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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With