Configure the Category - Post Relationship
In our previous lessons, we established the relationship between users and posts, enabling content ownership tracking.
Now we'll configure the relationship between categories and posts, which will allow us to organize blog content into thematic groups.
Understanding Category-Post Relationships
Each post in our blog system must belong to exactly one category, establishing a mandatory one-to-many relationship.
Let's modify our Post entity to include the category relationship:
@Entity
@Table(name = "posts")
public class Post {
// ... existing fields ...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", nullable = false)
private Category category;
// ... rest of the class ...
}Configuring the Category Side
The Category entity needs to maintain a collection of its associated posts.
Here's how we update the Category entity:
@Entity
@Table(name = "categories")
public class Category {
// ... existing fields ...
@OneToMany(mappedBy = "category")
private List<Post> posts = new ArrayList<>();
// ... rest of the class ...
}Understanding Fetch Types and Collections
The FetchType.LAZY configuration on the post side optimizes performance by loading category details only when explicitly accessed.
The initialization of the posts collection with new ArrayList<>() prevents null pointer exceptions when accessing the collection.
Cascade Considerations
We deliberately avoid cascade operations in this relationship because posts and categories have independent lifecycles.
Deleting a category shouldn't automatically delete its posts, as they might need to be reassigned to another category.
Similarly, deleting a post shouldn't affect its category.
Summary
- Posts must belong to exactly one category, enforced by a non-nullable foreign key
- Cascade operations are intentionally omitted to maintain data integrity
- Relationship validation occurs in the service layer rather than the entity level