【问题标题】:How to set foreign key nullable如何设置外键为空
【发布时间】:2019-02-15 23:51:00
【问题描述】:

我有一个类似于以下的类配置(只是一个示例,没有实际意义) -

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 值,但我的数据库包含null。我无法更改数据库或项目结构,所以有什么方法可以让我“合法”地向我的外键发出null 值,即不会产生异常。

【问题讨论】:

  • 没有理由 FK 不能为空。 joinColumn 注解有一个属性 nullable=true,你试过吗?
  • @NathanHughes 使用 nullable 无济于事,因为该字段仍然不可为空
  • @MarkusMauksch lemme 看看解决方案是否可行,谢谢
  • @monster 看起来您的解决方案应该在那里。在两个不同的页面上找到答案是没有用的:)

标签: java spring hibernate foreign-keys nullable


【解决方案1】:

使用@Column(nulable = true)

用于创建 DDL 脚本,不会带来想要的行为。

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

@ManyToOne(optional = true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多