Java @ManyToOne JPA 关系可以为空吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25718229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:00:07  来源:igfitidea点击:

Can a @ManyToOne JPA relation be null?

javahibernatejpahibernate-mappingmany-to-one

提问by Narges

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

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

Something like this:

像这样的东西:

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;

}

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

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

采纳答案by Vlad Mihalcea

You need to set:

您需要设置:

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

not optional=false.

不是optional=false

The @Column(nullable=true)is to instruct the DDL generation tool to include a NULLSQL column type constraint.

@Column(nullable=true)是指示DDL生成工具,包括NULLSQL列类型约束。

For more on optionalvs nullable, check out this StackOverflow answer.

有关optionalvs 的更多信息nullable,请查看此 StackOverflow 答案

回答by Sarwar kamal

try this:

尝试这个:

@JoinColumn(name = "subType_id", nullable = true)

回答by Oleksandr_DJ

Only this helped me:

只有这对我有帮助:

public class TopUp {
    @ManyToOne
    @JoinColumn(columnDefinition="integer", name="subtype_id")
    private SubType subType;
}

columnDefinition is a solution!

columnDefinition 是一个解决方案!