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.
I created an issue in the Hibernate issue tracker.
Java Prime Pack Here the entity classes are treated as relational tables (concept of JPA), therefore the relationships between Entity classes are as follows: @ManyToOne Relation. @OneToMany Relation. @OneToOne Relation.
You can use JPA's @MapsId annotation to tell Hibernate that it shall use the foreign key of an associated entity as the primary key. Let's take a look at a simple example. Each Book has a Manuscript, and each Manuscript belongs to 1 Book. The foreign key of the Book is also the primary key of the Manuscript.
If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side. The OneToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class.
Implementing With a Foreign Key in JPA. Note that we place the @OneToOne annotation on the related entity field, Address. Also, we need to place the @JoinColumn annotation to configure the name of the column in the users table that maps to the primary key in the address table.
Use name attribute of @JoinColumn. @JoinColumn(name="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With