Creating a primary key and composite primary key column – @Id and @IdClass

It's necessary to declare an Identity column in each class while developing with hibernate. Sometimes, when we need to declare a primary key as a combination of multiple columns, we call this the composite primary key, as the primary key is composed of multiple columns. We can declare a column with the primary key constraint and also generate a composite primary key using hibernate.

How to do it…

Let's start with a primary key declaration:

  1. To declare a column as a primary key column, we use the @Id annotation, as follows:
    @Id
    private long id;

    When the preceding code is executed, hibernate creates a column with the name id and also adds the primary key index to it. In this case, @Column is not required unless you want a custom column name.

  2. To declare it as a composite primary key, we will consider creating a composite primary key using the employee's first name and phone. Therefore, the firstName column will be duplicated, but the combination of both the firstName and phone column will never be duplicated. Let's take a look at how to achieve this by coding:
    @Entity
    @IdClass(Employee.class)
    public class Employee implements Serializable {
      @Id
      private String firstName;
    
      @Id
      private String phone;
    }

Here, we annotated the firstName and phone columns with @Id, which means that we want to create a primary key for both. Also, we annotated the entity class with the @IdClass annotation.

Note

Another thing that needs to be taken care of is that the entity class must implement Serializable if you plan to store the entity in any cache, session, or you wish to transfer the entity over wire. It is not necessary, but recommended.

The following table script shows how the composite primary key is generated:

CREATE TABLE `employee` (
  `phone` varchar(255) NOT NULL,
  `firstName` varchar(255) NOT NULL,
  PRIMARY KEY (`phone`,`firstName`)
);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.163.238