外键jpa / hibernate注释不能按预期工作

时间:2015-01-22 07:04:21

标签: java hibernate jpa orm

在实体中有两对协议:

import org.hibernate.annotations.ForeignKey;
...
@OneToOne(fetch = FetchType.LAZY, optional = false, targetEntity = UserSettingsEntityBean.class)
@JoinColumn(name = INTEGER_USER_ID)
@ForeignKey(name = "FK_USER_TO_SETTINGS")
private UserSettingsEntity userSettings;

@ManyToOne(targetEntity = DivisionEntityBean.class, optional = true)
@JoinColumn(name = "DIVISION_ID", nullable = true, columnDefinition = "integer")
@ForeignKey(name = "FK_USER_TO_DIVISIOG")
private DivisionEntity division;

Hibernate为这些ForeignKey注释生成以下更新: 正确的更新,如预期的那样:

alter table users add constraint FK_USER_TO_DIVISIOG foreign key (DIVISION_ID) references division

错误的数据库更新,注释被忽略(生成约束名称):

alter table users add constraint FK_olm1qeb13uc1worutbx1sc22k foreign key (USER_ID) references user_settings
你可以解释一下吗?有没有办法在第二种情况下设置约束名称?

UPDATED1:

以下解决方案也不起作用:

@JoinColumn(name = INTEGER_USER_ID, foreignKey = @javax.persistence.ForeignKey(name = "FK_USER_TO_PERS_DATA"))

此解决方案适用于ManyToOne,这是OneToOne的问题

UPDATED2: unit test to reproduce this issue

1 个答案:

答案 0 :(得分:0)

import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; 

@JoinColumn(updatable = false, nullable = false, foreignKey = @ForeignKey(name = "FK_customerUser_customer" ))
@ManyToOne(optional = false, cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
private Customer customer;