Spring Boot JPA One to Many Relationship Mapping Example

The Spring Boot JPA One to Many Relationship Mapping Example shows you the process of mapping an one-to-many relationship using Spring Data JPA and Spring Boot. A OneToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and if those target objects had the inverse relationship back to the source object it would be a ManyToOne relationship.

Other interesting posts you may like

Let’s begin:

Project structure
Our classic mvn project in this Spring Boot JPA One to Many Relationship Mapping Example.

Spring Boot JPA One to Many Relationship Mapping Example

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

One-To-Many Relationship
We are using a database named example_onetomany and two student and course tables . The course and student tables have a one-to-many relationship via course.id and student.course_id.
Here is the sql script

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

Student Entity

Course Entity

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.

@OneToMany and @ManyToOne annotations define a one-to-many and many-to-one relationship between 2 entities. @JoinColumn annotation indicates the 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 Many Relationship Mapping Example.

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

Donwload complete source code, click link below

spring-boot-jpa-one-to-many-example.zip (13 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons