Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

SOVANNARO
SOVANNARO

Posted on

     

Spring boot: JPA One-to-Many Mapping

Introduction

When building relational databases in Java, understanding how tomap relationships between entities is crucial. One of the most common relationships isOne-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:

  • WhatOne-to-Many mapping is.
  • How to implement it usingSpring 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?

AOne-to-Many relationship means thatone entity is related to multiple entities.

Real-World Examples:

  • A blog post can havemultiple comments.
  • A customer can havemultiple orders.
  • A department can havemultiple employees.

In database terms, this means theprimary key of one table is referenced as aforeign 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 aforeign key in the child table referencing the parent table’sprimary key.

📌 Step 1: Create thePost Entity

importjakarta.persistence.*;importjava.util.List;@EntitypublicclassPost{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)privateLongid;privateStringtitle;privateStringcontent;@OneToMany(mappedBy="post",cascade=CascadeType.ALL,orphanRemoval=true)privateList<Comment>comments;// Getters and Setters}
Enter fullscreen modeExit fullscreen mode

📌 Step 2: Create theComment Entity

importjakarta.persistence.*;@EntitypublicclassComment{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)privateLongid;privateStringtext;@ManyToOne@JoinColumn(name="post_id",nullable=false)privatePostpost;// Getters and Setters}
Enter fullscreen modeExit fullscreen mode

🔹Explanation:

  • ThePost entity has aList<Comment> to represent multiple comments.
  • @OneToMany(mappedBy = "post") inPost tells JPA thatComment owns the relationship.
  • TheComment entity has a@ManyToOne annotation with a@JoinColumn(name = "post_id") to store the foreign key.

💡Tip: Thecascade = CascadeType.ALL ensures that when aPost 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 athird table to manage the relationship.

📌 Modify thePost Entity

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

🔹 This approach creates apost_comments table that holdspost_id andcomment_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 maintaindata integrity (e.g., orders belonging to a customer).
✅ You want to avoiddata duplication while keeping a structured relationship.


Conclusion 🎯

In this article, we explored:

  • WhatOne-to-Many mapping is.
  • How to implement it inSpring 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 themost 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Passionate developer specializing in JavaScript, TypeScript, React, Vue, and Angular. I thrive on solving problems and building innovative solutions that make a difference in the modern world.
  • Location
    Phnom Penh, Cambodia
  • Education
    Phnom Penh International University (PPIU)
  • Work
    Front-End Developer building scalable apps, and mentoring juniors.
  • Joined

More fromSOVANNARO

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp