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, ...

Get Java Hibernate Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.