Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmbeddedId with foreign key

Tags:

java

orm

jpa

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;
}
like image 939
VANILKA Avatar asked Mar 01 '17 13:03

VANILKA


Video Answer


1 Answers

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.

like image 81
Maciej Kowalski Avatar answered Oct 19 '22 23:10

Maciej Kowalski