Narges Narges - 4 months ago 68
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(){
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;

public class TopUp{
@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?


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.