Can @ManyToOne's relation be null?

I have a table with the foreign key of another table (many-to-one relationship), but I want it to be zero.

Something like that:

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 a NullPointerException and says that the subtype cannot be null. Is there a way to get ManyToOne to accept null?

+7
java hibernate jpa hibernate-mapping many-to-one
source share
2 answers

You need to install:

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

not optional=false .

@Column(nullable=true) should indicate DDL generation to include the NULL SQL column type.

For more on optional vs nullable, check this SO answer .

+15
source share

try the following:

 @JoinColumn(name = "subType_id", nullable = true) 
+3
source share

All Articles