How to create Composite Primary Key – Spring JPA + Spring Boot + MySQL

In the tutorial, JavaSampleApproach will introduce step-by-step to create Composite Primary Key with @Embeddable annotation.

Related articles:
How to configure Spring JPA One to Many Relationship – SpringBoot

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.3.RELEASE
– MySql database

II. Overview

The tutorial will create a sample project with 2 entities: Customer entity (mapping with customer table) and OrderDetail entity (mapping with order_detail table). And they have One-to-Many relationship.
customer table has a composite primary key: {customer_id, brandcode}.
order_detail table has a primary key: order_id and a foreign key: {customer_id, brandcode}.

composite primary key - one-to-many relationship

To define a Composite Primary Key, we use javax.persistence.Embeddable annotation. @Embeddable is used to indicate a class whose instances are stored as intrinsic part of the owning entity.

Customer class:

CustomerId class:

OrderDetail class:

III. Practice

Step to do:
– Create Spring Boot project
– Create entities class
– Create JPA Repositories & Services
– Create a test client
– Configure JPA and datasource
– Run & check results

1. Create Spring Boot project

– Using SpringToolSuite, create a SpringBoot project. Then add needed dependencies:

2. Create entities class

– Create Customer entity:

– Create CustomerId class:

– Create OrderDetail entity:

3. Create JPA Repositories & Services
3.1 Create JPA repositories

– CustomerRepository:

– OrderRepository:

3.2 Create Services

– CustomerServices:

– OrderServices:

4. Create a test client

Use 2 services CustomerServices & OrderServices:

Implement 3 functions:
deleteAll()
saveData()
showAll()

Full Sourcecode:

5. Configure JPA and Datasource

– Open application.properties file, configure spring.datasource & spring.jpa:

– If set spring.jpa.generate-ddl is true, 2 tables: customer & order_detail will be created automatically by Hibernate.
Otherwise, if set spring.jpa.generate-ddl is false, we can use below SQL scripts to create the tables:

6. Run & check results

Build & Run the project with SpringBoot App mode.
-> Logs:

Database tables:

customer table data

composite primary key - embeddable class - customer table

order_detail table data

composite primary key - embeddable class - orderdetails table

III. SourceCode

SpringDataCompositePrimaryKey

By JavaSampleApproach | May 3, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*