This tutorial will walk you through the steps of mapping a JPA/Hibernate composite primary key entity example with Spring Boot, Spring Data JPA, Lombok, MySQL and Docker

What you'll need

  • JDK 8+ or OpenJDK 8+
  • Maven 3+
  • MySQL Server 5+ or Docker CE 18+

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── jpa
│       │               ├── book
│       │               │   ├──
│       │               │   └──
│       │               └──
│       └── resources
│           └──
├── Dockerfile
├── docker-compose.yml
└── pom.xml

Project dependencies

Define JPA Entity and Repository

Define JPA Entity

JPA Entity is defined by @Entity annotation, represent a table in your database.

Composite primary key is defined by a static class IdClass. It is linked to the entity by @IdClass class annotation and @Id field annotation.

Spring Data JPA Repository

Spring Data JPA contains some built-in Repository implemented some common functions to work with database such as findOne, findAll and save. All we need for this example is extends JpaRepository.

Define Properties and Creating Data

Application Properties

hk-mysql refers to Docker Compose service defined in the below docker-compose.yml file

spring.jpa.hibernate.ddl-auto=create allows JPA/Hibernate auto create database and table schema for you.

On production environment, you may like to disable the DDL Auto feature by using spring.jpa.hibernate.ddl-auto=validate or spring.jpa.hibernate.ddl-auto=none (default). Check out this example as one of the approaches
Database Migration/Evolution Example with Flyway and JPA/Hibernate

Creating data with JPA and Hibernate

Run the example

Run with Docker

Prepare Dockerfile for Java/Spring Boot application and docker-compose.yml for MySQL Server

Type the below command at the project root directory, make sure your local Docker is running

docker-compose up  

Access to MySQL Server docker container by issuing below bash command and key in hellokoding on Enter password:

docker exec -it hk-mysql mysql -p

Query the schema and data created by JPA/Hibernate based on your mapping

Run with JDK/OpenJDK, Maven and MySQL Server local

  • On, update data source user name + password to your local configs, update data source url hk-mysql to localhost
  • Then type this command at the project root directory mvn clean spring-boot:run

Source code

See also