Configure the User - Post Relationship

In our previous lessons, we created the foundational entities for our blog platform, including the User and Post entities.

Now we'll establish the relationship between users and their blog posts, enabling proper content ownership and management.

Understanding Entity Relationships

A blog post must always have an author, and this relationship needs to be enforced at the database level.

Let's modify our Post entity to include the author relationship:

@Entity @Table(name = "posts") public class Post { // ... existing fields ... @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id", nullable = false) private User author; // ... rest of the class ... }

Configuring the User Side

The User entity needs to maintain a collection of their posts.

Here's how we update the User entity:

@Entity @Table(name = "users") public class User { // ... existing fields ... @OneToMany(mappedBy = "author") private List<Post> posts = new ArrayList<>(); // ... rest of the class ... }

Understanding Fetch Types

The FetchType.LAZY configuration optimizes performance by loading post authors only when explicitly accessed.

This is particularly important for list operations where we might load many posts but not need their author details immediately.

Cascades

Let's now define the cascades for this relationship. Cascades define how changes to one entity affect the other.

As a Post should not be able to change its author, we'll not add cascades to the Post side of the relationship.

However, we'll want a user's posts to be deleted when we delete that user, so we'll add cascades to the User side of the relationship:

@Entity @Table(name = "users") public class User { // ... existing fields ... @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true) private List<Post> posts = new ArrayList<>(); // ... rest of the class ... }

Adding the cascade type of ALL here will ensure that a user's posts are deleted when that user is deleted.

It will also allow us to save new a Post if we add it to the posts collection and save the User.

Summary

  • The @ManyToOne annotation establishes the post-to-author relationship with a non-nullable foreign key
  • Lazy loading of author details optimizes performance for post listing operations
  • Helper methods ensure relationship consistency on both sides
  • Initialization of collections prevents null pointer exceptions
© 2026 Devtiro Ltd. All rights reserved