如何设置外键可空

问题描述 投票:0回答:1

我有一个类配置,如下所示(只是一个样本不是实际意义) -

public class payment
{
    @Id
    @Column("payment_id")
    private int paymentId;

    @ManyToOne
    @JoinColumn(name ="")
    private Fine fine;
    //getter setter and other stuff
}

public class Fine{
    @Id
    @Column("fine_id")
    private int fineId;

    @Column("amount")
    private int fineAmount;

    //other stuff
} 

我收到org.hibernate.ObjectNotFoundException: No row with the given identifier exists错误信息。根据answer,这是因为外键不能有null值但我的db包含null。我无法更改数据库或项目结构,所以有任何方式,以便我可以“合法地”发出null值到我的外键,即不创建异常。

java spring hibernate foreign-keys nullable
1个回答
0
投票

使用@Column(nulable = true)

用于创建DDL脚本,但不会带来所需的行为。

您需要将@ManyToOne标记为可选。

@ManyToOne(optional = true)
© www.soinside.com 2019 - 2024. All rights reserved.