DEV Community

SOVANNARO
SOVANNARO

Posted on

Spring boot: JPA One-to-Many Mapping

Introduction

When building relational databases in Java, understanding how to map relationships between entities is crucial. One of the most common relationships is One-to-Many mapping. In this guide, weโ€™ll break it down in a way thatโ€™s super easy to grasp and fun to learn! ๐Ÿคฉ

By the end of this article, youโ€™ll learn:

  • What One-to-Many mapping is.
  • How to implement it using Spring Boot, JPA, and Hibernate.
  • The different ways to set up the relationship.
  • Real-world use cases to apply in your projects.

Letโ€™s get started! ๐Ÿš€


Image description

What is One-to-Many Mapping?

A One-to-Many relationship means that one entity is related to multiple entities.

Real-World Examples:

  • A blog post can have multiple comments.
  • A customer can have multiple orders.
  • A department can have multiple employees.

In database terms, this means the primary key of one table is referenced as a foreign key in another table.

JPA makes this easy using the @OneToMany annotation. Letโ€™s see how to implement it! ๐Ÿ”ฅ


Implementing One-to-Many Mapping in Spring Boot

1๏ธโƒฃ One-to-Many Using a Foreign Key (Recommended โœ…)

The most common approach is to have a foreign key in the child table referencing the parent tableโ€™s primary key.

๐Ÿ“Œ Step 1: Create the Post Entity

import jakarta.persistence.*;
import java.util.List;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Step 2: Create the Comment Entity

import jakarta.persistence.*;

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String text;

    @ManyToOne
    @JoinColumn(name = "post_id", nullable = false)
    private Post post;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Explanation:

  • The Post entity has a List<Comment> to represent multiple comments.
  • @OneToMany(mappedBy = "post") in Post tells JPA that Comment owns the relationship.
  • The Comment entity has a @ManyToOne annotation with a @JoinColumn(name = "post_id") to store the foreign key.

๐Ÿ’ก Tip: The cascade = CascadeType.ALL ensures that when a Post is deleted, its comments are also removed. orphanRemoval = true helps keep the database clean!


2๏ธโƒฃ One-to-Many Using a Join Table ๐Ÿ›๏ธ

Sometimes, instead of a foreign key in the child table, you may want to use a third table to manage the relationship.

๐Ÿ“Œ Modify the Post Entity

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(
    name = "post_comments",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "comment_id")
)
private List<Comment> comments;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น This approach creates a post_comments table that holds post_id and comment_id as foreign keys, linking the two tables.


When to Use One-to-Many Mapping?

One-to-Many relationships are useful when:
โœ… An entity owns multiple child entities (e.g., a blog post with comments).
โœ… You need to maintain data integrity (e.g., orders belonging to a customer).
โœ… You want to avoid data duplication while keeping a structured relationship.


Conclusion ๐ŸŽฏ

In this article, we explored:

  • What One-to-Many mapping is.
  • How to implement it in Spring Boot using JPA.
  • Different approaches (foreign key vs. join table).
  • When to use it in real-world applications.

One-to-Many mapping is one of the most commonly used relationships in database design. Mastering it will make you a better backend developer! ๐Ÿš€

๐Ÿ’ฌ Got questions? Let me know in the comments! Happy coding! ๐Ÿ˜ƒ

Top comments (0)