我有两个实体,如下:
@Entity
public class Entity1
{
@Id
Long id;
@Basic
@OneToOne
@Column(unique=true,nullable=false)
String awesome;
...
}
and
@Entity
public class Entity2
{
@Id
Long id;
@OneToOne(mappedBy="awesome",targetEntity=Entity1.class)
@Column(name="myAwesome", insertable=false,updateable=false)
@Basic
String awesome; //FK to Entity1
}
我期望生成如下所示的 SQL:
Alter Table Entity1 Add Constraint Entity1Entity2_Awesome Foreign Key (myAwesome) References Entity1.Awesome
目前没有生成 SQL,我正在使用 eclipselink。
最佳答案
字符串不能是 OneToOne,并且您不能将某些内容标记为 Basic 和 OneToOne。
要创建 OneToOne 关系,请使用,
@OneToOne 实体2实体2;
所有关系都应该通过 Id 来表示,而不是通过非 id 字段(例如 Awesome)来表示。可以在 EclipseLink 中的非 Id 字段上定义外键,但不能在 JPA 中,为此您需要使用 DescriptorCustomizer。
一般来说关系应该是通过Id,所以要么重新考虑Id的关系。
关于java - JPA将非id字段映射为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585056/