Narges Narges - 1 month ago 20
Java Question

@ManyToOne relation can be null?

I have a table that have foreign key of another table(many to one relation) 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 exception nullpointer exception and says subtype can not be null
Is there any way to get the ManyToOne accept null?

Answer

You need to set:

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

not optional=false.

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

For more on optional vs nullable check this SO answer.