JPA map non-id field as foreign key
I have two entities as follows:
@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
}
I am expecting SQL to be generated that looks like this:
Alter Table Entity1 Add Constraint Entity1Entity2_Awesome Foreign Key (myAwesome) References Entity1.Awesome
Cur开发者_运维技巧rently no SQL is being generated, I am using eclipselink.
A String cannot be a OneToOne, and you can't mark something as a Basic and a OneToOne.
To create a OneToOne relationship use,
@OneToOne Entity2 entity2;
All relationships should be by Id, not by a non-id field such as awesome. It is possible to define a foreign key on a non-Id field in EclipseLink, but not in JPA, you would need to use a DescriptorCustomizer for this.
In general relationships should be by Id, so either reconsider the relationship of the Id.
I think you should use @JoinColumn here and explicitly specify names of column for join.
精彩评论