带外键的EmbeddedId [英] EmbeddedId with foreign key

查看:126
本文介绍了带外键的EmbeddedId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用引用另一个表的复合主键.我看到了很多主题,但没有答案适合我.

I am trying to have Composite Primary Key with Reference to Another table. I saw many topics, but no answers works in my case.

在我的数据库中,未添加外键为owner_id正确创建的列.因此,即使员工不存在,我也可以添加新记录. 我使用SQLLite作为数据库

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

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;

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;

    // …

}

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

推荐答案

您距离很近.

您应该使用与该外键相对应的类字段名称,而不是在@MapsId批注中使用列名称:

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;

由于@Column已在@Embeddable中指定,因此无需再次指定.还不需要referencedColumnName,因为您指向的是目标ID字段,默认情况下,该字段由持久性提供程序选择.

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.

这篇关于带外键的EmbeddedId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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