Practical coding guides

JPA and Hibernate One To One Relationship Mapping Example with Spring Boot, Spring Data JPA and MySQL

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

What you will 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
│       │           │   │   ├── Book.java
│       │           │   │   ├── BookDetail.java
│       │           │   │   ├── BookDetailRepository.java
│       │           │   │   └── BookRepository.java
│       │           │   └── JpaApplication.java
│       │           └── springboot
│       └── resources
│           └── application.properties
├── Dockerfile
├── docker-compose.yml
└── pom.xml

Project dependencies


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






Define JPA Entities and Repositories

One-To-One 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, library and address tables have a one-to-one relationship. A library has only one address, and an address is the address of only one library.

JPA One to One

library.address_id is a foreign key references to address.id.

Try this example if the relationship owner uses its foreign key as primary key JPA/Hibernate One To One Shared Primary Key Bidirectional Relationship Mapping

Define JPA and Hibernate Entities

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


package com.hellokoding.jpa.book;

import lombok.Data;

import javax.persistence.*;


public class Library {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(unique = true)
    private Address address;

    public Library(String name, Address address) {
        this.name = name;
        this.address = address;


package com.hellokoding.jpa.book;

import lombok.Data;

import javax.persistence.*;


public class Address {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String street;

    private String zipCode;

    @OneToOne(mappedBy = "address")
    private Library library;

    public Address(String street, String zipCode) {
        this.street = street;
        this.zipCode = zipCode;

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

unique = true enforces the unique constraint, 1 address belongs to only 1 library.

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.


package com.hellokoding.jpa.book;

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

public interface LibraryRepository extends JpaRepository<Library, Integer>{

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.

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 Address will be saved at the same time with the owner Library without the need of calling its save function explicitly


package com.hellokoding.jpa;

import com.hellokoding.jpa.book.Address;
import com.hellokoding.jpa.book.Library;
import com.hellokoding.jpa.book.LibraryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application implements CommandLineRunner {
    private final LibraryRepository libraryRepository;

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

    public void run(String... args) {
        // Create a couple of Library and Address
        libraryRepository.save(new Library("Library 1", new Address("Street 1", "Zip 1")));
        libraryRepository.save(new Library("Library 2", new Address("Street 2", "Zip 2")));

Run the example

Run with Docker

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


FROM maven:3.5-jdk-8


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

    build: .
    - .:/app
    - ~/.m2:/root/.m2
    working_dir: /app
    command: mvn clean spring-boot:run
    - 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

JPA One to One

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


Follow HelloKoding