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.
Let's start with a primary key declaration:
@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.
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.
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`) );