如何在@OneToOne关系中设置@JoinColumn和@MapsId的外键名称

nyx*_*yxz 8 java hibernate foreign-keys hibernate-5.x

在下面的例子中(来自Vlad Mihalcea关于"使用JPA和Hibernate映射@OneToOne关系的最佳方法"的帖子):

@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
}
Run Code Online (Sandbox Code Playgroud)

我之间的单向关系PostDetailsPost实体,重新使用的ID Post作为ID PostDetails使用@MapsId.

除此之外我还补充说

@JoinColumn(foreignKey = @ForeignKey(name = "fk_post"))
Run Code Online (Sandbox Code Playgroud)

因为我想给外键提供自定义名称.不幸的是,Hibernate忽略了我的自定义名称,并为外键分配了自己随机生成的名称.

所以问题是如何在这种情况下设置外键名称(使用时@MapsId)?我试图逃脱而不必使用已弃用的Hibernate @ForeignKey注释.

我测试过的Hibernate版本是5.2.125.2.13.

我希望我遗漏了一些东西,但这对我来说似乎是一个Hibernate错误,考虑到HK在早期版本中有多少与FK名称有关的问题.

更新

在Hibernate问题跟踪器中创建了一个问题.

小智 1

使用@JoinColumn的name属性。@JoinColumn(名称=“”)