Spring Boot JPA One to One Shared Primary Key Example

The Spring Boot JPA One to One Shared Primary Key Example shows you the process of mapping an one-to-one relationship using Spring Data JPA and Spring Boot. A OneToOne relationship in Java is where the source object has an attribute that references another target object and (if) that target object had the inverse relationship back to the source object it would also be a OneToOne relationship.

Other interesting posts you may like

Let’s begin:

Project structure
Our classic mvn project in this Spring Boot JPA One to One Shared Primary Key Example.

Spring Boot JPA One to One Shared Primary Key Example

Maven dependencies
Our Spring Boot JPA One to One Shared Primary Key Example will use JPA, MySQL, so that we must add these dependencies in the pom.xml

One-To-One Relationship
We are using a database named example_onetoone and two student and student_detail tables . The student and student_detail tables have a one-to-one relationship via student.id and student_detail.student_id.
Here is the sql script

Create JPA Entities
Entity class Student and StudentDetail are simple POJO class. Here we are using class Student and StudentDetail with JPA @Entity annotation to map them to a database tables (these tables were created in above step).

Student Entity

StudentDetail Entity


Let’s dig deeper:

@Table annotation maps the entity with the table. If no @Table is omitted, the default value is used. It means that the class name of the entity maps with the table.

@Id annotation marks the identifier property of the entity.

@Column application maps the entity’s field with the table’s column. If @Column is omitted, the default value is used. It means that the field name of the entity maps with the table’s column.

@OneToOne annotation defines a one-to-one relationship with another entity. The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the “other” entity.

Spring Data JPA Repository
In this example, we all need to extend the JpaRepository. This is a built-in Repository implemented some common functions to work with database: findOne, findAll, save,etc.

Properties Configuration

Create SpringBootApplication class

DEMO
You can go to the project directory on the console screen and run the command line

Or create the unit test class, for example

Run the above test class and see the output like below

That’s all on the Spring Boot JPA One to One Shared Primary Key Example.

References
One-to-One Relationships
Spring Boot – Database initialization

Download compelete source code, click link below

springboot-jpa-onetoone-sharedprimarykey-mysql.zip (19 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons