Skip to content

freddyDOTCMS/springboot-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Spring Boot Tutorial Application

A comprehensive Spring Boot tutorial application demonstrating REST API development, JPA relationships, and modern Spring Boot best practices. This application serves as a learning resource for understanding Spring Boot concepts through a practical blog system with authors, posts, and comments.

πŸš€ Features

Core Functionality

  • Author Management: Create and retrieve authors with full name and email
  • Post Management: Create and retrieve blog posts with title, content, and excerpts
  • Comment System: Add comments to posts with nested resource patterns
  • RESTful API: Complete REST API with proper HTTP methods and status codes
  • Database Integration: JPA/Hibernate with automatic schema generation

Technical Features

  • Layered Architecture: Controllers, Services, Repositories, and Entities
  • Data Transfer Objects (DTOs): Clean separation between API and domain layers
  • Exception Handling: Global exception handling with proper HTTP status codes
  • Object Mapping: MapStruct for type-safe object transformations
  • Performance Optimization: @EntityGraph for N+1 query prevention
  • Dependency Injection: Spring's IoC container with @Autowired and @Qualifier

πŸ—οΈ Architecture

Technology Stack

  • Spring Boot 3.x: Main framework
  • Spring Data JPA: Data access layer
  • H2 Database: In-memory database for development
  • MapStruct: Object mapping library
  • Thymeleaf: Template engine for web views
  • Maven: Build tool and dependency management

Project Structure

src/main/java/com/example/
β”œβ”€β”€ PostApplication.java              # Main application class
β”œβ”€β”€ AppController.java               # Web controller for main page
β”œβ”€β”€ GlobalExceptionHandler.java      # Global exception handling
β”œβ”€β”€ NotFoundEntityException.java     # Base exception class
β”œβ”€β”€ author/                         # Author domain
β”‚   β”œβ”€β”€ Author.java                 # JPA entity
β”‚   β”œβ”€β”€ AuthorRepository.java       # Spring Data repository
β”‚   β”œβ”€β”€ AuthorService.java          # Business logic
β”‚   β”œβ”€β”€ AuthorController.java       # REST controller
β”‚   β”œβ”€β”€ AuthorMapper.java           # Object mapper
β”‚   β”œβ”€β”€ CreateAuthorRequest.java    # Input DTO
β”‚   β”œβ”€β”€ AuthorResponse.java         # Output DTO
β”‚   └── AuthorNotFoundException.java # Specific exception
β”œβ”€β”€ post/                          # Post domain
β”‚   β”œβ”€β”€ Post.java                  # JPA entity with relationships
β”‚   β”œβ”€β”€ PostRepository.java        # Repository with @EntityGraph
β”‚   β”œβ”€β”€ PostService.java           # Service with cross-service collaboration
β”‚   β”œβ”€β”€ PostController.java        # REST controller
β”‚   β”œβ”€β”€ PostMapper.java            # MapStruct mapper
β”‚   β”œβ”€β”€ PostDetailMapper.java      # Specialized mapper
β”‚   β”œβ”€β”€ CreatePostRequest.java     # Input DTO with relationships
β”‚   β”œβ”€β”€ PostResponse.java          # Basic output DTO
β”‚   β”œβ”€β”€ PostDetailResponse.java    # Detailed output DTO
β”‚   └── PostNotFoundException.java # Specific exception
└── post/comment/                  # Comment domain
    β”œβ”€β”€ Comment.java               # JPA entity with lazy loading
    β”œβ”€β”€ CommentRepository.java     # Repository
    β”œβ”€β”€ CommentService.java        # Service
    β”œβ”€β”€ CommentController.java     # REST controller (nested resources)
    β”œβ”€β”€ CommentMapper.java         # Object mapper
    β”œβ”€β”€ CreateCommentRequest.java  # Input DTO
    └── CommentResponse.java       # Output DTO

πŸ› οΈ Prerequisites

  • Java 17 or higher
  • Maven 3.6 or higher
  • IDE (IntelliJ IDEA, Eclipse, or VS Code recommended)

πŸ“¦ Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd springboot-tutorial

2. Build the Project

mvn clean install

3. Run the Application

java -jar target/post-0.0.1-SNAPSHOT.jar

The application will start on http://localhost:8080

🌐 API Endpoints

Authors

  • GET /api/authors - Get all authors
  • GET /api/authors/{id} - Get author by ID
  • POST /api/authors - Create a new author

Posts

  • GET /api/posts - Get all posts (basic info)
  • GET /api/posts/{id} - Get post by ID (with comments)
  • POST /api/posts - Create a new post

Comments

  • POST /api/posts/{postId}/comments - Create a comment for a post

πŸ“ API Examples

Create an Author

curl -X POST http://localhost:8080/api/authors \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@example.com"
  }'

Create a Post

curl -X POST http://localhost:8080/api/posts \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My First Blog Post",
    "content": "This is the content of my first blog post...",
    "excerpt": "A brief summary of the post content",
    "authorId": 1
  }'

Create a Comment

curl -X POST http://localhost:8080/api/posts/1/comments \
  -H "Content-Type: application/json" \
  -d '{
    "text": "This is a great post! Thanks for sharing."
  }'

Get Post with Comments

curl http://localhost:8080/api/posts/1

🎯 Key Spring Boot Concepts Demonstrated

1. @SpringBootApplication

  • Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan
  • Entry point for the Spring Boot application

2. JPA Annotations

  • @Entity: Marks classes as JPA entities
  • @Id & @GeneratedValue: Primary key configuration
  • @OneToMany & @ManyToOne: Relationship mapping
  • @JoinColumn: Foreign key specification

3. Spring Data JPA

  • JpaRepository: Automatic CRUD operations
  • @EntityGraph: Performance optimization
  • Query method generation

4. REST Controllers

  • @RestController: JSON response handling
  • @RequestMapping: URL mapping
  • @GetMapping & @PostMapping: HTTP method mapping
  • @PathVariable & @RequestBody: Parameter binding

5. Dependency Injection

  • @Autowired: Automatic dependency injection
  • @Qualifier: Bean qualification
  • @Service, @Repository, @Controller: Component stereotypes

6. Exception Handling

  • @ControllerAdvice: Global exception handling
  • @ExceptionHandler: Specific exception handling
  • Custom exception hierarchy

7. Object Mapping

  • MapStruct for type-safe object transformations
  • @Mapper and @Mapping annotations
  • Multi-parameter mapping

πŸ—„οΈ Database

The application uses H2 in-memory database by default. The database schema is automatically generated from JPA entities:

Tables

  • author: Authors with id, first_name, last_name, email
  • post: Posts with id, title, content, excerpt, author_id (FK)
  • comment: Comments with id, text, post_id (FK)

Relationships

  • Author β†’ Post: One-to-Many (one author can have many posts)
  • Post β†’ Comment: One-to-Many (one post can have many comments)

πŸ”§ Configuration

Application Properties

The application uses src/main/resources/application.properties for configuration:

# Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

## πŸ“š Learning Objectives

This tutorial application demonstrates:

1. **Spring Boot Fundamentals**
   - Auto-configuration
   - Component scanning
   - Dependency injection

2. **JPA and Database Integration**
   - Entity mapping
   - Relationship management
   - Repository pattern

3. **REST API Development**
   - RESTful design principles
   - HTTP method mapping
   - Request/response handling

4. **Architecture Patterns**
   - Layered architecture
   - DTO pattern
   - Service layer pattern

5. **Exception Handling**
   - Global exception handling
   - Custom exceptions
   - HTTP status code mapping

6. **Performance Optimization**
   - Lazy loading
   - Eager loading with @EntityGraph
   - N+1 query prevention

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published