What is a Null Constraint in JPA
Null constraints in JPA reflect the nullability of a column as defined in the database schema. As such in all database definitions a column is nullable by default. I.e. if a column is not defined as primary key or unique then it is by default nullable. It is to make a column mandatory, i.e. to stop it from accepting null values, that we make it non-nullable. The same logic is reflected in JPA as well.
Null constraints in JPA can be defined on either a
@Column or a
@JoinColumn. Lets say we have an EMPLOYEE table which is related to a PARKINGSLOT table. We would like to make the social security number of the employee as non-nullable and also the foreign-key column(ass=”nl-code-intext”>@JoinColumn) as non-nullable. Lets have a look at the Employee POJO entity with the null constraints added to it –
The corresponding EMPLOYEE table definition would look like this –
Important Note – If you are auto generating the POJO entities then you will notice one more thing. The POJO has a constructor defined which takes as parameters all the non-null fields of the entity. Hence, when you add or remove not-nullable fields from a POJO entity you also need to add or remove the corresponding parameters from this constructor to keep the constructor definition consistent.