In the following example (from Vlad Mihalcea's post on "The best way to map a @OneToOne relationship with JPA and Hibernate"):
@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(name = "fk_post"))
@MapsId
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
//Getters and setters omitted for brevity
}
I have a unidirectional relationship between PostDetails
and Post
entities, reusing the ID of Post
as ID for the PostDetails
using @MapsId
.
In addition to that I've added
@JoinColumn(foreignKey = @ForeignKey(name = "fk_post"))
because I wanted to give custom name to the foreign key. Unfortunately Hibernate disregarded my custom name and assigned its own randomly generated name for the foreign key.
So the question is how do I set foreign key name in this case (when using @MapsId
)? I try to get away without having to use the deprecated Hibernate @ForeignKey
annotation.
Hibernate versions I've tested this on are 5.2.12
and 5.2.13
.
I hope I'm missing something but it seems like a Hibernate bug to me at this point, taking in consideration how many issues with FK names Hibernate had in previous versions.
Update
I created an issue in the Hibernate issue tracker.