SpringBoot JPA @OneToMany Mapping : Fetch data from tables

SpringBoot JPA @OneToMany Mapping as name says we will see one to many mapping in SpringBoot and JPA.

First see the ER Diagram

SpringBoot JPA @OneToMany Mapping ER Diagram

Following is the Entity Relationship Diagram for user, user_mails and user_mobiles table.

One user can have multiple mail ids.

So this is a one to many relation.

similarly one user can have multiple mobile numbers.

This is also one to many mapping.

user’s id in user table is

Fig: Entity Relationship Diagram

Tools/Technology used

  1. Spring Boot 2.2
  2. JPA
  3. Eclipse IDE
  4. MySQL Database

SpringBoot JPA @OneToMany Mapping Directory Structure

SpringBoot  JPA @OneToMany Mapping Project Directory Structure
Fig: Project Directory Structure

To build project we used maven and included

  1. spring-boot-starter-web
  2. spring-boot-starter-data-jpa
  3. mysql-connector-java

You can also use spring Initializr to generate POM.xml

POM.xml

Application.properties file configuration

MySQL database is used.

Configuration with MySQL is as specified below

Entities

We have created three entity files User, UserMail and UserMobile.

Tables and columns are mapped in entity file.

User.java

To access multiple mail and mobile numbers user is mapped with UserMail and UserMobile entities.

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set userMails = new HashSet(0);

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set userMobiles = new HashSet(0);

@oneToMany mapping is used and few parameters are also used.

  1. mappedBy- a property name in userMails. Based on this property matching oneToMany mapping will be performed.
  2. cascade- Transactions that are performing on table will also perform on mapped table or not.
  3. fetch – specifies when to access mapped data from join table

UserMail.java

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;

Here User Object is mapped as Many to one.

The @JoinColumn specified based on which (user_mail) column it will perform join and fetch data.

@JsonIgnore- This will ignored the json result and prevent the loop.

UserMobiles

UserDAO.java

UserDAO is responsible for fetching data from database.

UserService.java

UserController.java

Here we have used RestController to show data on index position

Result

On running above project we will get following data.

Result of @OneToMany Mapping
Fig: Result of @OneToMany Mapping

Read More

Angular Spring Boot Showing Data In Table