Saturday 6 July 2019

Jpa: @Column: Specify whether this column takes nullable values or not


By using 'nullable' attribute of @Column annotation, you can specify whether a column can take null values or not.

@Entity(name = "MY_EMPLOYEE")
public class Employee {

         @Column(name = "EMPLOYEE_FIRST_NAME", nullable = false)
         private String firstName;

         @Column(name = "EMPLOYEE_LAST_NAME", nullable = true)
         private String lastName;
        
         .....
         .....
        
}

In the above example, firstName is not allowed to take nullable values, lastName can take nullable values.

Find the below working example.

Employee.java
package com.sample.myApp.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity(name = "MY_EMPLOYEE")
public class Employee {

 @Id
 @GeneratedValue
 @Column(name = "EMPLOYEE_ID")
 private int id;

 @Column(name = "EMPLOYEE_FIRST_NAME", nullable = false)
 private String firstName;

 @Column(name = "EMPLOYEE_LAST_NAME", nullable = true)
 private String lastName;

 @Column(name = "EMPLOYEE_EMAIL", unique = true)
 private String email;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
 }

}

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
 xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="myPersistenceUnit"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

  <class>com.sample.myApp.entities.Employee</class>

  <properties>
   <property name="eclipselink.target-database" value="Derby" />
   <property name="javax.persistence.jdbc.driver"
    value="org.apache.derby.jdbc.ClientDriver" />
   <property name="javax.persistence.jdbc.url"
    value="jdbc:derby://localhost:1527/demoDatabase;create=true" />
   <property name="javax.persistence.jdbc.user" value="APP" />
   <property name="javax.persistence.jdbc.password" value="APP" />
   <property name="eclipselink.logging.level" value="INFO" />
   

   <property name="eclipselink.ddl-generation"
    value="drop-and-create-tables" />

   <property name="eclipselink.ddl-generation.output-mode"
    value="database" />
  </properties>

 </persistence-unit>
</persistence>


TestApp.java
package com.sample.myApp;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sample.myApp.entities.Employee;

public class TestApp {

 private static void printEmployees(EntityManager em) {
  System.out.println("**************************************");
  Query q = em.createQuery("SELECT e from MY_EMPLOYEE e", Employee.class);
  List<Employee> emps = q.getResultList();
  for (Employee emp1 : emps) {
   System.out.println(emp1);
  }
  System.out.println("**************************************\n");
 }

 private static void addEmployee(Employee emp, EntityManager em) {
  em.getTransaction().begin();
  em.persist(emp);
  em.getTransaction().commit();
 }

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee();
   emp.setFirstName("Siva");
   emp.setLastName("Majety");
   emp.setEmail("abc@abc.com");

   addEmployee(emp, em);
   printEmployees(em);

   emp = new Employee();
   emp.setFirstName("Manoj");
   emp.setLastName(null);
   emp.setEmail("xyz@xyz.com");

   addEmployee(emp, em);
   printEmployees(em);
   
   emp = new Employee();
   emp.setFirstName(null);
   emp.setLastName(null);
   emp.setEmail("tuv@tuv.com");

   addEmployee(emp, em);
   printEmployees(em);
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


When you run TestApp.java, you will endup in ‘SQLIntegrityConstraintViolationException’.

[EL Info]: 2018-06-28 09:06:28.543--ServerSession(1978869058)--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Info]: connection: 2018-06-28 09:06:30.076--ServerSession(1978869058)--/file:/C:/Users/krishna/java9/jpaDemo/target/classes/_myPersistenceUnit login successful
**************************************
Employee [id=1, firstName=Siva, lastName=Majety, email=abc@abc.com]
**************************************

**************************************
Employee [id=1, firstName=Siva, lastName=Majety, email=abc@abc.com]
Employee [id=2, firstName=Manoj, lastName=null, email=xyz@xyz.com]
**************************************

[EL Warning]: 2018-06-28 09:06:30.893--UnitOfWork(221111433)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Column 'EMPLOYEE_FIRST_NAME'  cannot accept a NULL value.
Error Code: 20000
Call: INSERT INTO MY_EMPLOYEE (EMPLOYEE_ID, EMPLOYEE_EMAIL, EMPLOYEE_FIRST_NAME, EMPLOYEE_LAST_NAME) VALUES (?, ?, ?, ?)
 bind => [4 parameters bound]


Project structure looks like below.

Previous                                                    Next                                                    Home

No comments:

Post a Comment