I'll walk through implementing a feature for a blog post management system with commenting functionality. This will demonstrate full-stack development using Spring Boot and React.
Analysis Phase
Backend (Spring Boot):
- Post and Comment entities
- REST controllers
- Service layer
- Repository layer
- DTOs for data transfer
- Security configuration
Frontend (React):
- Post list and detail components
- Comment components
- API integration services
- State management
- Form handling
Technology Stack:
- Spring Boot 3.x
- Spring Data JPA
- Spring Security
- PostgreSQL
- React 18
- TypeScript
- Axios for API calls
- React Query for state management
Planning Phase
Architecture Overview
- Backend will provide RESTful APIs for post and comment management
- Frontend will consume these APIs and handle UI state
- JWT authentication for secure access
Step-by-Step Implementation Plan
- Backend Database Schema and Entities
- Backend APIs and Services
- Frontend Components and State Management
- Integration and Authentication
Understanding Validation Scenarios
Scenario 1: Creating a Blog Post
- Input: Post title, content, author
- Expected: New post created, returned with generated ID
- Validation: Title length, content requirements, author authentication
Scenario 2: Adding Comments
- Input: Comment text, post ID, commenter
- Expected: Comment added to post, notification sent
- Validation: Comment length, post existence, user authentication
Scenario 3: Listing Posts with Comments
- Input: Page number, size
- Expected: Paginated posts with associated comments
- Validation: Proper ordering, pagination limits
Reasoning for Design Choices
- Using DTOs to separate entity and API concerns
- Implementing pagination for performance
- Using React Query for efficient cache management
- TypeScript for type safety and better developer experience
Implementation Phase
Backend Implementation
- Entity Classes
// src/main/java/com/blog/model/Post.java
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT")
private String content;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();
@CreatedDate
private LocalDateTime createdAt;
// Getters, setters, constructors
}
// src/main/java/com/blog/model/Comment.java
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;
@CreatedDate
private LocalDateTime createdAt;
// Getters, setters, constructors
}
- DTOs
// src/main/java/com/blog/dto/PostDTO.java
public record PostDTO(
Long id,
String title,
String content,
LocalDateTime createdAt,
List<CommentDTO> comments
) {}
// src/main/java/com/blog/dto/CommentDTO.java
public record CommentDTO(
Long id,
String content,
LocalDateTime createdAt
) {}
- Service Layer
// src/main/java/com/blog/service/PostService.java
@Service
@Transactional
public class PostService {
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
/**
* Creates a new blog post
* @param postDTO The post data to create
* @return The created post
* @throws ValidationException if the post data is invalid
*/
public PostDTO createPost(PostDTO postDTO) {
validatePost(postDTO);
Post post = new Post();
post.setTitle(postDTO.title());
post.setContent(postDTO.content());
Post savedPost = postRepository.save(post);
return mapToDTO(savedPost);
}
/**
* Retrieves paginated posts
* @param pageable Pagination information
* @return Page of posts with comments
*/
public Page<PostDTO> getPosts(Pageable pageable) {
return postRepository.findAll(pageable)
.map(this::mapToDTO);
}
private void validatePost(PostDTO postDTO) {
if (postDTO.title() == null || postDTO.title().trim().isEmpty()) {
throw new ValidationException("Post title cannot be empty");
}
if (postDTO.content() == null || postDTO.content().length() < 10) {
throw new ValidationException("Post content must be at least 10 characters");
}
}
private PostDTO mapToDTO(Post post) {
return new PostDTO(
post.getId(),
post.getTitle(),
post.getContent(),
post.getCreatedAt(),
post.getComments().stream()
.map(this::mapToCommentDTO)
.collect(Collectors.toList())
);
}
}
- Controller Layer
// src/main/java/com/blog/controller/PostController.java
@RestController
@RequestMapping("/api/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping
public ResponseEntity<PostDTO> createPost(@RequestBody @Valid PostDTO postDTO) {
return ResponseEntity.ok(postService.createPost(postDTO));
}
@GetMapping
public ResponseEntity<Page<PostDTO>> getPosts(
@PageableDefault(size = 10) Pageable pageable
) {
return ResponseEntity.ok(postService.getPosts(pageable));
}
}
Frontend Implementation
- API Service
// src/services/postApi.ts
import axios from 'axios';
import { PostDTO, CommentDTO } from '../types';
const API_BASE = '/api';
export const postApi = {
/**
* Fetches paginated posts
* @param page Page number (0-based)
* @param size Items per page
*/
getPosts: async (page: number, size: number) => {
const response = await axios.get<Page<PostDTO>>(
`${API_BASE}/posts?page=${page}&size=${size}`
);
return response.data;
},
/**
* Creates a new post
* @param post Post data to create
*/
createPost: async (post: Omit<PostDTO, 'id' | 'createdAt' | 'comments'>) => {
const response = await axios.post<PostDTO>(`${API_BASE}/posts`, post);
return response.data;
}
};
- React Components
// src/components/PostList.tsx
import { useQuery } from '@tanstack/react-query';
import { postApi } from '../services/postApi';
export const PostList: React.FC = () => {
const { data, isLoading, error } = useQuery({
queryKey: ['posts'],
queryFn: () => postApi.getPosts(0, 10)
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading posts</div>;
return (
<div className="post-list">
{data?.content.map(post => (
<PostCard key={post.id} post={post} />
))}
</div>
);
};
// src/components/CreatePost.tsx
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { postApi } from '../services/postApi';
export const CreatePost: React.FC = () => {
const queryClient = useQueryClient();
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const createPostMutation = useMutation({
mutationFn: postApi.createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] });
setTitle('');
setContent('');
}
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
createPostMutation.mutate({ title, content });
};
return (
<form onSubmit={handleSubmit}>
<input
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="Post title"
/>
<textarea
value={content}
onChange={e => setContent(e.target.value)}
placeholder="Post content"
/>
<button type="submit">Create Post</button>
</form>
);
};
Conclusion
This implementation provides a solid foundation for a blog post system with:
- Robust backend with proper validation and error handling
- Type-safe frontend with efficient state management
- Clear separation of concerns
- Scalable architecture
Future considerations:
- Add user authentication and authorization
- Implement real-time comments using WebSocket
- Add rich text editing for posts
- Implement image upload functionality
- Add search and filtering capabilities