How Do You Define Sequence Generated Primary Key In Hibernate Average ratng: 4,5/5 9937 reviews

In this article, You’ll learn how to map a composite primary key in Hibernate using JPA’s @Embeddable and @EmbeddedId annotations.

Let’s say that We have an application that manages Employees of various companies. Every employee has a unique employeeId within his company. But the same employeeId can be present in other companies as well, So we can not uniquely identity an employee just by his employeeId.

SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence. I prefer to use the GenerationType.SEQUENCE because it is very efficient and allows Hibernate to decide when to perform the insert statement. SEQUENCES are much more flexible than IDENTIFIER columns because: A SEQUENCE is table free and the same sequence can be assigned to multiple columns or tables. A SEQUENCE may preallocate values to improve performance. A SEQUENCE may define an incremental step, allowing us to benefit from a “pooled” Hilo algorithm.

To identify an employee uniquely, we need to know his employeeId and companyId both. Check out the following Employees table that contains a composite primary key which includes both the employeeId and companyId columns -

Hibernate annotations with composite primary key I want to know how to use hibernate annotations in case of composite primary key in one table. I tried like this, I have created a table without primary key. Just use the @Id annotation which lets you define which property is the identifier of your entity. You don't need to use the @GeneratedValue annotation because I don't think you want hibernate to generate this property for you. Even in the XML configuration based approach its an optional tag and can be skipped.

Let’s create a project from scratch and learn how to map such composite primary key using JPA and Hibernate.

Creating the Project

You can generate the project quickly using Spring Boot CLI by typing the following command in the terminal -

Alternatively, You can also use Spring Initializr web app to generate the project. Follow the instructions below to generate the app using Spring Initializr web app -

  1. Open http://start.spring.io
  2. Enter Artifact as “jpa-composite-primary-key-demo”
  3. Click Options dropdown to see all the options related to project metadata.
  4. Change Package Name to “com.example.jpa”
  5. Select Web, JPA and Mysql dependencies.
  6. Click Generate to generate and download the project.

How Do You Define Sequence Generated Primary Key In Hibernate 10

Following is the directory structure of the complete application for your reference -

(Your bootstrapped project won’t have model and repository packages and all the other classes. We’ll create them as we proceed to next sections)

Configuring the Database and Hibernate Log Levels

Let’s add the MySQL database URL, username and password configurations in src/main/resources/application.properties file -

Apart from MySQL database configurations, I’ve also specified hibernate log levels and other properties.

The property spring.jpa.hibernate.ddl-auto = update keeps the Entity types in your application and the mapped database tables in sync. Whenever you update a domain entity, the corresponding mapped table in the database will also get updated when you restart the application next time.

This is great for development because you don’t need to manually create or update the tables. They will automatically be created/updated based on the Entity classes in your application.

Before proceeding to the next section, Please make sure that you create a MySQL database named jpa_composite_pk_demo and change spring.datasource.username and spring.datasource.password properties as per your MySQL installation.

Defining the Domain model

A composite primary key is mapped using an Embeddable type in hibernate. We’ll first create an Embeddable type called EmployeeIdentity containing the employeeId and companyId fields, and then create the Employee entity which will embed the EmployeeIdentity type.

Hibernate

Create a new package named model inside com.example.jpa package and then add the following classes inside the model package -

1. EmployeeIdentity - Embeddable Type

2. Employee - Domain model

In the Employee class, We use @EmbeddedId annotation to embed the EmployeeIdentity type and mark it as a primary key.

Sequence

Creating the Repository

Next, Let’s create the repository for accessing the Employee data from the database. First, Create a new package named repository inside com.example.jpa package, then add the following interface inside the repository package -

Code to test the Composite Primary Key Mapping

Finally, Let’s write some code to test the composite primary key mapping. Open the main class JpaCompositePrimaryKeyDemoApplication.java and replace it with the following code -

We first clean up the Employee table and then insert a new Employee record with an employeeId and a companyId to test the setup.

You can run the application by typing mvn spring-boot:run from the root directory of the project. The Employee record will be inserted in the database once the application is successfully started.

Querying using the Composite Primary Key

Let’s now see some query examples using the composite primary key -

1. Retrieving an Employee using the composite primary key - (employeeId and companyId)

How Do You Define Sequence Generated Primary Key In Hibernate Mode

2. Retrieving all employees of a particular companyRsa key pair generator.

Let’s say that you want to retrieve all the employees of a company by companyId. For doing this, just add the following method in the EmployeeRepository interface.

That’s all! You don’t need to implement anything. Spring Data JPA will dynamically generate a query using the method name. You can use the above method in the main class to retrieve all the employees of a company like this -

US, UK)State or Province: Enter the complete state name, please be sure to not abbreviate or shorten it. Save the certificate by browsing the file name and click Finish.Country Name: Enter the two-letter code without punctuation of the respective country (i.e. Generate private key from certificate request. New York, not NY)Locality or City: The locality field is the city or town name.

Conclusion

How Do You Define Sequence Generated Primary Key In Hibernate In Ct

Congratulations guys! In this article, you learned how to implement a composite primary key in hibernate using @Embeddable and @EmbeddedId annotations.

You can find the entire source code for the sample project that we built in this article in my jpa-hibernate-tutorials github repository.

How Do You Define Sequence Generated Primary Key In Hibernate 2017

Thanks for reading. See you in the next post.