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 - Employee.java with 'not null' constraint
//Employee.java
 @Entity
 public class Employee {
 @Id 
 private int employeeId;
 
 @Column(nullable=false)
 private String socialSecurityNumber;
 
 @OneToOne
 @JoinColumn(name="PARKING_SLOT_ID",nullable=false)
 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
 EMPLOYEE_ID INT(10)(P.K);
 PARKING_SLOT_ID INT(10) NOT NULL(F.K);
 SOCIAL_SECURITY_NUMBER VARCHAR(10) NOT NULL;
 EMP_ADDRESS VARCHAR(100);
 - - 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-2016 JavaBrahman.com, all rights reserved.
  • sulfuret

    I was able to find good info from your blog articles.

  • music free

    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 .

  • calligraphie arabe

    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!

  • black tenmoku japanese

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

    • java brahman

      Thanks for the appreciation :)