Create the Category Entity
In our previous lesson, we created the User entity as the foundation for user management.
Now we'll implement the Category entity, which will provide a way to organize blog posts into broad groups.
Understanding Categories in Blog Systems
Blog categories serve as high-level containers that group related content together.
Categories differ from tags in that they represent broad, predefined classifications rather than flexible, user-defined keywords.
Implementing the Category Entity
Here's our initial implementation:
package com.devtiro.blog.domain.entities;
import jakarta.persistence.*;
import lombok.*;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(nullable = false, unique = true)
private String name;
// Custom equals implementation needed to avoid Lombok's implementation
// which can cause issues with JPA entity lifecycle management
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}Summary
- Categories provide a hierarchical organization structure for blog content
- Custom
equalsandhashCodemethods ensure proper JPA entity behavior - The
uniqueconstraint on category names prevents duplicates - Using
UUIDas the primary key supports distributed systems and security