How to configure Spring JPA One to One Relationship – SpringBoot

This tutorial will guide you through the steps of configuring Spring JPA One to One relationship with Spring Boot and MySql.

Related articles:
Spring JPA One to Many Relationship
Spring JPA – Many to Many relationship


I. Technologies

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

II. Practice – Spring JPA One to One Relationship

Step to do
– Create SpringBoot project
– Create Models
– Create JPA Repositories
– Configure Datasource & Spring JPA
– Implement a test Client
– Run & Check results

1. Create SpringBoot project

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

2. Create Models

Create 2 entities Wife and Husband that having One-to-One relationship:

Spring JPA One to One relationship

2.1 Wife entity

2.2 Husband entity

@Entity: Specifies that the class is an entity. This annotation is applied to the entity class.
@Id: Specifies the primary key of an entity.
@OneToOne: Defines a single-valued association to another entity that has one-to-one multiplicity.
@JoinColumn: Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

3. Create JPA Repositories

Create 2 interface repositories by extends JpaRepository:

WifeRepository.java

HusbandRepository.java

4. Configure Datasource & Spring JPA

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

5. Implement a test Client

Use 2 repository: WifeRepository & HusbandRepository:

Implement 3 functions:
clearData() is used to empty 2 tables wife & husband
saveData() is used to persist entities (Wife & Husband) to database
showData() is used to load all records (Wife & Husband) and show all on console.

Full SourceCode:

6. Run & Check results

Build & Run the project with SpringBoot App mode.

Hibernate Logs:

Application’s Logs:

Database data:

1. wife table

wife

2. husband table

husbands

III. SourceCode

SpringJPAOneToOne


Related Posts



Got Something To Say:

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

*