JPA Not Null Constraint / Not Nullable column

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 –

POJO - with 'not null' constraint
 public class Employee {
 private int employeeId;
 private String socialSecurityNumber;
 private ParkingSlot parkingSlot;

// Getters/Setters and rest of the code

The corresponding EMPLOYEE table definition would look like this –

EMPLOYEE table with 'not null' constraint
 - - rest of the table definition goes here

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.


Digiprove sealCopyright © 2014-2017, all rights reserved.

Comments on “JPA Not Null Constraint / Not Nullable column”

  1. Hi my friend! I wish to say that this post is awesome, great written and come with approximately all important infos.

    I’d like to look more posts like this .

  2. Woah! I’m really enjoying the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between usability and visual appearance.
    I must say you’ve done a awesome job with this. Also, the blog
    loads extremely fast for me on Opera. Superb Blog!

  3. Hi there, I enjoy reading through your post. I like to write a little comment to support you.

Comments are closed.