@ManyToOne JPA关系可以为null吗? [英] Can a @ManyToOne JPA relation be null?

查看:2381
本文介绍了@ManyToOne JPA关系可以为null吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表有另一个表的外键(多对一关系),但我希望它可以为空。

I have a table that has foreign key of another table (many to one relationship) but i want it to be nullable.

这样的事情:

public class SubType() {

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

}

public class TopUp {

    @Column(nullable = true)
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private SubType subType;

}

但是 @Column(nullable = true)抛出 NullPointerException 并说子类型不能为null。
有没有办法让ManyToOne接受null?

But @Column(nullable = true) throws the NullPointerException and says subtype can not be null. Is there any way to get the ManyToOne accept null?

推荐答案

你需要设置:

@ManyToOne(optional = true, fetch = FetchType.LAZY)

不是可选= false

@Column(nullable = true)用于指示DDL生成包含NULL SQL列类型。

The @Column(nullable=true) is to instruct the DDL generation to include a NULL SQL column type.

有关可选vs可空的更多信息查看此SO答案

For more on optional vs nullable check this SO answer.

这篇关于@ManyToOne JPA关系可以为null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆