OneToOne使用主键与nullable为true和关系的关系

时间:2013-07-03 10:20:47

标签: java hibernate foreign-keys hibernate-mapping one-to-one

我有两个具有OneToOne关系的实体:

@Entity
@Table(name = "APPLICATION_DEVICE")
public class ApplicationDevice implements Serializable {

[...]

    @Id
    public ApplicationDeviceKey getApplicationDeviceKey()
    {
        return applicationDeviceKey;
    }

    @NotFound(action = NotFoundAction.IGNORE)
@OneToOne(cascade=CascadeType.ALL)
@JoinColumns( {
    @JoinColumn(name = "applicationId", referencedColumnName = "applicationId",insertable=false,updatable=false, nullable = true),
    @JoinColumn(name = "deviceId", referencedColumnName = "deviceId",insertable=false,updatable=false, nullable = true), }
)
public ApplicationDevicePushInfo getDevicePushInfo() {
    return devicePushInfo;
}

和另一个实体:

 @Entity
 @Table(name = "APPLICATION_DEVICE_PUSHINFO")
 public class ApplicationDevicePushInfo implements Serializable {

 [...]
 @Id
public ApplicationDeviceKey getApplicationDeviceKey()
{
    return applicationDeviceKey;
}

 @OneToOne
@JoinColumns( {
    @JoinColumn(name = "applicationId", referencedColumnName = "applicationId",insertable=false,updatable=false, nullable = false),
    @JoinColumn(name = "deviceId", referencedColumnName = "deviceId",insertable=false,updatable=false, nullable = false)}
)
public ApplicationDevice getApplicationDevice() {
    return applicationDevice;
}

第二个实体可以为null,当我尝试存储我的第一个实体时,我得到一个:

 Cannot add or update a child row: a foreign key constraint fails (`malcom_dev`.`application_device`, CONSTRAINT `FK16A0C0451DC7C799` FOREIGN KEY (`applicationId`, `deviceId`) REFERENCES `APPLICATION_DEVICE_PUSHINFO` (`applicationId`, `deviceId`))

默认情况下,nullable为true,所以我认为这种关系是可能的。

还有另一种方法可以使用oneToOne关系的实体而不创建新的列或表,并允许第二个实体为空吗?

1 个答案:

答案 0 :(得分:1)

这不是Hibernate而是数据库异常。看起来表上有外键约束。

删除外键约束后,它将起作用。