Close

JPA - Applying Unique Constraints by using @Column#unique

[Last Updated: Oct 22, 2018]

The attribute 'unique' of @Column annotation can be used to apply unique constraints to the selected field.

@Column annotation:

package javax.persistence;
 ....
@Target({METHOD, FIELD}) 
@Retention(RUNTIME)
public @interface Column {
 ....
    /**
     * (Optional) Whether the column is a unique key.  This is a 
     * shortcut for the <code>UniqueConstraint</code> annotation at the table 
     * level and is useful for when the unique key constraint 
     * corresponds to only a single column. This constraint applies 
     * in addition to any constraint entailed by primary key mapping and 
     * to constraints specified at the table level.
     */
    boolean unique() default false;
 ....
}

Also see last tutorial to understand how to apply UniqueConstraint annotation at the table level.

Example

Entity

@Entity
@Table
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  @Column(unique = true)
  private String name;
  private String dept;
    .............
}

Main class

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          //constraint assigned to Employee table:
          runNativeQuery("SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='EMPLOYEE'");
          //column names of CONSTRAINTS table:
          runNativeQuery("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='CONSTRAINTS'");
          persistEmployees();
          findAllEmployees();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void findAllEmployees() {
      System.out.println("-- Employees with phone number NOT 222-222-222 --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      TypedQuery<Employee> query = entityManager
              .createQuery("Select e from Employee e", Employee.class);
      List<Employee> list = query.getResultList();
      list.forEach(System.out::println);
      entityManager.close();
  }

  private static void runNativeQuery(String s) {
      System.out.printf("-- %s --%n", s);

      EntityManager entityManager = entityManagerFactory.createEntityManager();
      Query query = entityManager.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.of("Diana", "IT");
      Employee employee2 = Employee.of("Mike", "Admin");
      Employee employee3 = Employee.of("Tim", "Sales");

      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee1);
      em.persist(employee2);
      em.persist(employee3);
      em.getTransaction().commit();
      em.close();
  }
}
-- SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='EMPLOYEE' --
[TEST, PUBLIC, UK_K2HV0HTYU32375G0IWVRUB0FM, UNIQUE, TEST, PUBLIC, EMPLOYEE, UK_K2HV0HTYU32375G0IWVRUB0FM_INDEX_7, null, NAME, , ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT PUBLIC.UK_K2HV0HTYU32375G0IWVRUB0FM UNIQUE(NAME) INDEX PUBLIC.UK_K2HV0HTYU32375G0IWVRUB0FM_INDEX_7, 9]
[TEST, PUBLIC, CONSTRAINT_7, PRIMARY_KEY, TEST, PUBLIC, EMPLOYEE, PRIMARY_KEY_7, null, ID, , ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT PUBLIC.CONSTRAINT_7 PRIMARY KEY(ID) INDEX PUBLIC.PRIMARY_KEY_7, 7]
-- SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='CONSTRAINTS' --
CONSTRAINT_CATALOG
CONSTRAINT_SCHEMA
CONSTRAINT_NAME
CONSTRAINT_TYPE
TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
UNIQUE_INDEX_NAME
CHECK_EXPRESSION
COLUMN_LIST
REMARKS
SQL
ID
-- Employees with phone number NOT 222-222-222 --
Employee{id=1, name='Diana', dept='IT'}
Employee{id=2, name='Mike', dept='Admin'}
Employee{id=3, name='Tim', dept='Sales'}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.197: H2 Database Engine.
  • hibernate-core 5.3.6.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • hibernate-jpamodelgen 5.3.6.Final: Annotation Processor to generate JPA 2 static metamodel classes.
  • JDK 1.8
  • Maven 3.5.4

JPA - @Column#unique Example Select All Download
  • jpa-column-annotation-unique-constraints
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
          • resources
            • META-INF

    See Also