Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 24

Mastering One-to-Many and Many-to-One Relationships

This lesson is built with resources from youtube.com, javapro.academy and 1 more site.

Hello! Welcome back to the course.

In our last lesson, we built a UserRepository that gave us full CRUD capabilities for our User entity. This is a solid foundation, but a blog platform isn't much without posts. This brings us to a fundamental concept in application design: relationships between data.

Today's goal is to connect users to their posts by implementing a classic one-to-many relationship. A user can have many posts, but each post belongs to exactly one user. By the end of this lesson, you will master the learning outcome: "Define @OneToMany and @ManyToOne relationships between entities (e.g., User and Post)."

We will create a new Post entity and link it to our existing User entity using the standard, most efficient practices in JPA.

1. Relationships: MERN vs. Spring Boot

In your experience with the MERN stack and MongoDB, you've likely handled relationships in one of two ways:

  1. Embedding: Storing an array of post documents directly inside a user document.
  2. Referencing: Storing an array of ObjectIds in the user document that reference documents in a separate posts collection, or storing a single userId in each post document.

Relational databases, which JPA is built for, use the second approach exclusively, but with a more formal structure: foreign keys. The posts table will contain a user_id column that points to the id of a specific user in the users table.

Our task is to tell JPA how to manage this foreign key relationship using Java annotations.

One-to-Many Foreign Key Mapping Strategy in JPA
This diagram shows how a one-to-many relationship is structured. In our case, `EntityA` is the `User` and `EntityB` is the `Post`. The `Post` table will contain the foreign key linking back to the `User`.

2. The Best Way to Map @OneToMany

There are several ways to map a one-to-many relationship in JPA, but one approach is widely considered the most efficient and robust for production systems: the bidirectional association. This means both the User entity will know about its Posts, and the Post entity will know about its User.

The following article by Vlad Mihalcea, a leading expert on JPA and Hibernate, is the definitive guide on this topic. It explains the pitfalls of other approaches and why the bidirectional method is superior.

The best way to map a @OneToMany relationship with JPA and Hibernate

This article explains why the bidirectional @OneToMany association is the most efficient mapping. It's a dense read, but it provides deep insight into how JPA works under the hood.

Please read the "Introduction" and the section titled "Bidirectional @OneToMany". Focus on understanding: Why the @ManyToOne side is crucial for controlling the relationship. The roles of mappedBy, cascade, and orphanRemoval in the @OneToMany annotation. The purpose of the addComment and removeComment helper methods.

Let's put this theory into practice by building the relationship for our blog platform.


3. Hands-On: Building the Relationship

We'll start with the "many" side of the relationship, our new Post entity.

Step 1: Create the Post Entity (The "Many" Side)

  1. In your domain package, create a new class named Post.java.
  2. Populate it with the following code. We'll break it down piece by piece.
package com.example.blogplatform.domain;

import jakarta.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "posts")
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Lob // Specifies that this should be mapped to a large object column type
    @Column(nullable = false, columnDefinition = "TEXT")
    private String content;

    @Column(name = "created_at", updatable = false)
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    // --- The 'Many' side of the relationship ---
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    public Post() {
        this.createdAt = LocalDateTime.now();
        this.updatedAt = LocalDateTime.now();
    }
    
    // Getters, Setters, etc.
    // ... we will add them via IDE generation
}

Let's focus on the new annotations:

  • @ManyToOne: This annotation defines the relationship. It tells JPA that many Post entities can be linked to one User.
  • fetch = FetchType.LAZY: This is a critical performance optimization. It means that when you load a Post, JPA will not automatically load the associated User from the database. The User will only be fetched when you explicitly access it (e.g., by calling post.getUser()). The default for @ManyToOne is EAGER, which can lead to fetching too much data and is often a source of performance issues (the famous N+1 problem, which we'll discuss later).
  • @JoinColumn(name = "user_id", nullable = false): This specifies the details of the foreign key.
    • name = "user_id": This is the name of the foreign key column that will be created in our posts table.
    • nullable = false: This enforces that every post must belong to a user. The user_id cannot be null.

This Post entity is now the owning side of the relationship because it physically contains the foreign key (@JoinColumn).

Step 2: Update the User Entity (The "One" Side)

Now, let's update User.java to complete the other side of the bidirectional relationship.

  1. Open your User.java file.
  2. Add a List<Post> field and the associated @OneToMany annotation.
// Inside your User.java class

// ... existing fields (id, firstName, etc.)

import java.util.ArrayList;
import java.util.List;

// ...

@OneToMany(
    mappedBy = "user",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<Post> posts = new ArrayList<>();

// Getters, setters, and now... helper methods!
// ...

Let's dissect this annotation:

  • @OneToMany: Declares that one User can be associated with many Posts.
  • mappedBy = "user": This is the most important part. It tells JPA: "Don't create a new join table for this relationship. The relationship is already managed by the user field in the Post class." This makes the User the inverse side (or non-owning side) of the relationship. Without mappedBy, JPA would incorrectly create a third table (user_posts) to manage the association, which is inefficient.
  • cascade = CascadeType.ALL: This is a convenience for persistence. It means that any operation (persist, remove, merge, etc.) performed on a User entity will be cascaded to its associated Post entities. If you save a new User that has Posts in its list, the posts will be saved too. If you delete a User, all their posts will be deleted.
  • orphanRemoval = true: If you remove a Post from a User's posts list, that Post entity becomes an "orphan" and will be automatically deleted from the database.

Step 3: Ensure Bidirectional Consistency

In Java, the link between a User and a Post is not automatic. If you call post.setUser(user), the user.getPosts() list is not automatically updated. You must manage both sides of the association yourself. The best practice is to create helper methods on the owning side's parent (User) to handle this synchronization.

Add these two methods to your User.java class:

// Inside User.java

public void addPost(Post post) {
    posts.add(post);
    post.setUser(this);
}

public void removePost(Post post) {
    posts.remove(post);
    post.setUser(null);
}

Now, instead of manually setting both sides, you can simply call user.addPost(post), and the relationship will be correctly established in your object model.

UML Diagram of Bidirectional One-to-Many Relationship (Post and PostComment)
This diagram visualizes the bidirectional relationship we've just built. Note the `addComment` and `removeComment` methods on the `Post` entity, which serve the same purpose as our `addPost` and `removePost` methods.

4. Runtime Observation & Debugging

Let's see our work in action and run a debugging exercise.

First, generate the getters and setters for all new fields in both User.java and Post.java using your IDE.

Next, update the DataInitializer.java to test the new relationship. Replace its content with the following:

package com.example.blogplatform;

import com.example.blogplatform.domain.Post;
import com.example.blogplatform.domain.User;
import com.example.blogplatform.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;

    public DataInitializer(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("--- DELETING ALL USERS ---");
        userRepository.deleteAll(); // Clean up from previous runs

        System.out.println("--- STARTING DATA INITIALIZATION ---");

        // 1. Create a User
        User user = new User();
        user.setFirstName("Jane");
        user.setLastName("Doe");
        user.setEmail("jane.doe@example.com");
        user.setPassword("securepassword456");

        // 2. Create Posts
        Post post1 = new Post();
        post1.setTitle("My First Post");
        post1.setContent("This is the content of my first post.");

        Post post2 = new Post();
        post2.setTitle("JPA Relationships");
        post2.setContent("Understanding JPA relationships is key.");

        // 3. Associate Posts with User using our helper method
        user.addPost(post1);
        user.addPost(post2);

        // 4. Save the User. Thanks to CascadeType.ALL, posts will be saved too.
        userRepository.save(user);

        System.out.println("--- DATA INITIALIZATION COMPLETE ---");
    }
}

Now, run your application. Look at the console output. You should see three insert statements:

Hibernate: 
    insert 
    into
        users
        (email, first_name, last_name, password) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        posts
        (created_at, content, title, updated_at, user_id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        posts
        (created_at, content, title, updated_at, user_id) 
    values
        (?, ?, ?, ?, ?)

Notice how Hibernate correctly inserts the user_id into the posts table. This is the efficient mapping we want!

Debugging Task: The Unwanted Join Table

Let's break it to understand it better.

  1. Stop the application.
  2. Go to User.java and comment out mappedBy = "user" from the @OneToMany annotation.
  3. Run the application again.

Now, inspect the SQL logs. You'll see something very different and far less efficient:

Hibernate: 
    insert into users (...) values (...)
Hibernate: 
    insert into posts (...) values (...) -- Note: user_id is NOT set here!
Hibernate: 
    insert into posts (...) values (...) -- Note: user_id is NOT set here!
Hibernate: 
    create table users_posts (user_id bigint not null, posts_id bigint not null)
Hibernate:
    alter table if exists users_posts add constraint UK_... unique (posts_id)
Hibernate: 
    insert into users_posts (user_id, posts_id) values (?, ?)
Hibernate: 
    insert into users_posts (user_id, posts_id) values (?, ?)

Hibernate has created a third "join table" (users_posts) to manage the relationship. This is the default behavior for a unidirectional @OneToMany and is exactly what we want to avoid. It's less efficient for a simple one-to-many case.

To fix this, undo your change and add mappedBy = "user" back. This is one of the most common mistakes beginners make with JPA, and now you know how to spot and fix it by observing the generated SQL.


Conclusion

Excellent work! You have successfully modeled a core relationship in our application, adhering to production-level best practices for JPA.

Key Takeaways:

  • A bidirectional association is the most efficient way to map a one-to-many database relationship in JPA.
  • The @ManyToOne side is the owning side and defines the @JoinColumn (the foreign key).
  • The @OneToMany side is the inverse side and must use mappedBy to refer to the field on the owning side. This prevents the creation of an inefficient join table.
  • Helper methods (like addPost/removePost) are essential for maintaining object consistency on both sides of the relationship.
  • Setting fetch = FetchType.LAZY is a critical performance optimization to avoid over-fetching data.

Preview of the Next Lesson:

Now that our entities are linked, we need to query them. How do we find all posts for a specific user? Or find a user by their email? In the next lesson, we will "Write custom repository queries using both derived query method names and the @Query annotation with JPQL" to build powerful and expressive data access methods.