I am trying to have Composite Primary Key with Reference to Another table. I saw many topics, but no answers works in my case.
In my database the columns are correctly created by foreign key for owner_id
was not added. So I can add new record even when employee doesn't exist.
I use SQLLite
as database
Class a:
@Column(name = "filename", unique = true)
private String filename;
@EmbeddedId
private TimeSheetID id;
@MapsId("owner_id")
@JoinColumn(name = "owner_id", referencedColumnName = "employee_id")
@ManyToOne
private EmployeeeEntity employee;
Class B
public class TimeSheetID implements Serializable{
private static final long serialVersionUID = 7469844076039968866L;
@Column(nullable = false, name = "period")
private String period;
@Column(nullable = false, name = "owner_id")
private String ownerId;
// …
}
Class C
@Column(nullable = false)
public String getName() {
return name;
}
@Id
@Column(name = "employee_id")
public String getEmployeeID() {
return employeeID;
}
@Column(nullable = false)
public String getBusinessUnit() {
return businessUnit;
}
You were quite close.
Instead of using a column name in the @MapsId
annotation you should use the class field name which corresponds to that foreign key:
@MapsId("ownerId")
@ManyToOne
private EmployeeeEntity employee;
Also as the @Column
is already specified in the @Embeddable
you do not need to specify it again. There referencedColumnName
also is not needed as your are pointing to the targets id field, which is choosen by the persistent provider by default.
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