How to set Foreign key name in @OneToOne relation with @JoinColumn and @MapsId
Asked Answered
A

1

15

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.

Ascites answered 22/2, 2018 at 12:31 Comment(1)
Still a problem with Hibernate 5.3.15 despite github.com/hibernate/hibernate-orm/pull/2566. Hibernate Jira issues similar to this: hibernate.atlassian.net/browse/HHH-12320 hibernate.atlassian.net/browse/HHH-12975 hibernate.atlassian.net/browse/HHH-11180Wei
I
1

Use name attribute of @JoinColumn. @JoinColumn(name="")

Intersexual answered 12/9, 2020 at 1:56 Comment(1)
e.g @JoinColumn(name="pidFk")Intersexual

© 2022 - 2024 — McMap. All rights reserved.