HelloKoding

Practical coding guides

JPA and Hibernate One To One Shared Primary Key Relationship Mapping Example with Spring Boot and MySQL

This tutorial will walk you through the steps of mapping a JPA and Hibernate One to One shared primary key bidirectional entity relationships example with Spring Boot, Spring Data JPA, Lombok, MySQL and Docker

What you will need

  • Your favorite IDE
  • 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
│       │               │   ├── Address.java
│       │               │   ├── AddressRepository.java
│       │               │   ├── Library.java
│       │               │   └── LibraryRepository.java
│       │               └── Application.java
│       └── resources
│           └── application.properties
├── Dockerfile
├── docker-compose.yml
└── pom.xml

Project dependencies

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hellokoding.jpa</groupId>
    <artifactId>jpa-hibernate-one-to-one-shared-primary-key-mysql</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Define JPA Entities and Repositories

One-To-One Shared Primary Key Relationship

One to one relationship refers to the relationship between two entities/tables A and B in which one item/row of A may be linked with only one item/row of B, and vice versa.

In this example, book and book_detail tables have a one-to-one relationship. A book has only one book detail, and a book detail belong to only one book.

JPA One to One Shared

book_detail.book_id is a foreign key references to book.id. book_detail also uses its foreign key book_id as primary key so-called shared primary key.

Define JPA Entities

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

Book.java

package com.hellokoding.jpa.book;

import lombok.*;

import javax.persistence.*;

@Data

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @OneToOne(mappedBy = "book", cascade = CascadeType.ALL)
    private BookDetail bookDetail;

    public Book(String name, BookDetail bookDetail) {
        this.name = name;
        this.bookDetail = bookDetail;
        this.bookDetail.setBook(this);
    }
}

BookDetail.java

package com.hellokoding.jpa.book;

import lombok.Data;

import javax.persistence.*;

@Data

@Entity
public class BookDetail {
    @Id
    private Integer id;

    @OneToOne
    @JoinColumn
    @MapsId
    private Book book;

    private int numberOfPages;

    public BookDetail(int numberOfPages) {
        this.numberOfPages = numberOfPages;
    }
}

@Id declares the entity identifier.

@Column maps the entity’s field with the table’s column. If @Column is omitted, the field name of the entity will be used as column name by default.

@OneToOne defines a one-to-one relationship between 2 entities.

@JoinColumn defines foreign key column and indicates the owner of the relationship.

mappedBy indicates the inverse of the relationship.

@MapsId defines embedded primary key, book_detail.book_id is embedded from book.id.

Spring Data JPA Repository

Spring Data JPA contains some built-in Repository abstracting common functions based on EntityManager to work with database such as findAll, findById, save, delete, deleteById. All we need for this example is extends JpaRepository.

BookRepository.java

package com.hellokoding.jpa.book;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Integer>{
}

BookDetailRepository.java

package com.hellokoding.jpa.book;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookDetailRepository extends JpaRepository<BookDetail, Integer>{
}

Define Properties and Creating data

Application Properties

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=hellokoding
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true

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.

In practice, 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 Spring Boot Flyway Example of Database Evolution

Creating data with JPA and Hibernate

Thanks to CascadeType.ALL, associated entity BookDetail will be saved at the same time with Book without the need of calling its save function explicitly

JpaApplication.java

package com.hellokoding.jpa;

import com.hellokoding.jpa.book.Book;
import com.hellokoding.jpa.book.BookDetail;
import com.hellokoding.jpa.book.BookRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@RequiredArgsConstructor
@SpringBootApplication
public class JpaApplication implements CommandLineRunner {
    private final BookRepository bookRepository;

    public static void main(String[] args) {
        SpringApplication.run(JpaApplication.class, args);
    }

    @Override
    public void run(String... args) {
        // Create a couple of Book and BookDetail
        bookRepository.save(new Book("Hello Koding 1", new BookDetail(101)));
        bookRepository.save(new Book("Hello Koding 2", new BookDetail(102)));
    }
}

Run the example

Run with Docker

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

Dockerfile

FROM maven:3.5-jdk-8

docker-compose.yml

version: '3'
services:
  hk-mysql:
    container_name: hk-mysql
    image: mysql/mysql-server:5.7
    environment:
      MYSQL_DATABASE: test
      MYSQL_ROOT_PASSWORD: hellokoding
      MYSQL_ROOT_HOST: '%'
    ports:
    - "3306:3306"
    restart: always

  app:
    build: .
    volumes:
    - .:/app
    - ~/.m2:/root/.m2
    working_dir: /app
    command: mvn clean spring-boot:run
    depends_on:
    - hk-mysql

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 schema and data created by JPA/Hibernate based on your mapping

JPA One to One Shared

JPA One to One Shared

Run with JDK/OpenJDK, Maven and MySQL Server local

Update hk-mysql on application.properties to localhost and type the below command at the project root directory

mvn clean spring-boot:run

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/jpa-hibernate-examples/jpa-hibernate-one-to-one-shared-primary-key-mysql

Follow HelloKoding