Skip to content

ngcodhub/student-crud-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Student CRUD Application

A complete Student Management System built with Spring Boot, demonstrating all CRUD (Create, Read, Update, Delete) operations with proper validation, error handling, and best practices.

πŸš€ Features

  • Complete CRUD Operations for Student management
  • Input Validation with detailed error messages
  • Global Exception Handling for consistent error responses
  • Sample Data Initialization for testing
  • H2 In-Memory Database for development
  • RESTful API Design following best practices
  • Comprehensive Logging for debugging
  • Unit Tests for controllers
  • Detailed Code Comments for beginners

πŸ“ Project Structure

src/
β”œβ”€β”€ main/
β”‚   β”œβ”€β”€ java/com/example/demo/
β”‚   β”‚   β”œβ”€β”€ DemoApplication.java          # Main Spring Boot application class
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   └── DataInitializer.java      # Sample data initialization
β”‚   β”‚   β”œβ”€β”€ controller/
β”‚   β”‚   β”‚   └── StudentController.java    # REST API endpoints
β”‚   β”‚   β”œβ”€β”€ dto/
β”‚   β”‚   β”‚   β”œβ”€β”€ StudentRequestDTO.java    # Request data transfer object
β”‚   β”‚   β”‚   └── StudentResponseDTO.java   # Response data transfer object
β”‚   β”‚   β”œβ”€β”€ entity/
β”‚   β”‚   β”‚   └── Student.java              # JPA entity for database
β”‚   β”‚   β”œβ”€β”€ exception/
β”‚   β”‚   β”‚   β”œβ”€β”€ ErrorResponse.java        # Error response structure
β”‚   β”‚   β”‚   β”œβ”€β”€ GlobalExceptionHandler.java # Global error handling
β”‚   β”‚   β”‚   └── ValidationErrorResponse.java # Validation error structure
β”‚   β”‚   β”œβ”€β”€ repository/
β”‚   β”‚   β”‚   └── StudentRepository.java    # Data access layer
β”‚   β”‚   └── service/
β”‚   β”‚       β”œβ”€β”€ StudentService.java       # Business logic interface
β”‚   β”‚       └── impl/
β”‚   β”‚           └── StudentServiceImpl.java # Business logic implementation
β”‚   └── resources/
β”‚       └── application.properties        # Application configuration
└── test/
    └── java/com/example/demo/
        └── controller/
            └── StudentControllerTest.java # Unit tests for controller

πŸ› οΈ Technologies Used

  • Java 17 - Programming language
  • Spring Boot 3.5.7 - Framework
  • Spring Data JPA - Database access
  • Spring Boot Validation - Input validation
  • H2 Database - In-memory database
  • Lombok - Reduces boilerplate code
  • Maven - Build tool
  • JUnit 5 - Testing framework

πŸƒβ€β™‚οΈ Running the Application

Prerequisites

  • Java 17 or higher
  • Maven (or use included Maven wrapper)

Steps to Run

  1. Clone or download the project

  2. Navigate to project directory

    cd demo
  3. Run the application

    ./mvnw spring-boot:run
  4. Application will start on port 8080

    http://localhost:8080
    
  5. Access H2 Database Console (optional)

    http://localhost:8080/h2-console
    
    • JDBC URL: jdbc:h2:mem:studentdb
    • Username: sa
    • Password: (leave empty)

πŸ“ API Documentation

Base URL: http://localhost:8080/api/students

Sample Data

The application automatically creates 5 sample students:

  • John Doe (Computer Science, Active)
  • Jane Smith (Business Administration, Active)
  • Mike Johnson (Engineering, Active)
  • Emily Davis (Psychology, Inactive)
  • David Wilson (Computer Science, Active)

πŸ”„ CRUD Operations

1. CREATE - Add New Student

Endpoint: POST /api/students

Request Body:

{
  "firstName": "Alice",
  "lastName": "Brown",
  "email": "alice.brown@email.com",
  "age": 21,
  "course": "Mathematics",
  "phoneNumber": "1111222233",
  "dateOfBirth": "2002-06-15",
  "address": "123 University Ave",
  "isActive": true
}

Response (201 Created):

{
  "id": 6,
  "firstName": "Alice",
  "lastName": "Brown",
  "fullName": "Alice Brown",
  "email": "alice.brown@email.com",
  "age": 21,
  "course": "Mathematics",
  "phoneNumber": "1111222233",
  "dateOfBirth": "2002-06-15",
  "address": "123 University Ave",
  "isActive": true
}

cURL Command:

curl -X POST http://localhost:8080/api/students \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "Alice",
    "lastName": "Brown",
    "email": "alice.brown@email.com",
    "age": 21,
    "course": "Mathematics",
    "phoneNumber": "1111222233",
    "dateOfBirth": "2002-06-15",
    "address": "123 University Ave",
    "isActive": true
  }'

2. READ - Get All Students

Endpoint: GET /api/students

Response (200 OK):

[
  {
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "fullName": "John Doe",
    "email": "john.doe@email.com",
    "age": 20,
    "course": "Computer Science",
    "phoneNumber": "1234567890",
    "dateOfBirth": "2003-05-15",
    "address": "123 Main Street, City, State",
    "isActive": true
  }
  // ... more students
]

cURL Command:

curl -X GET http://localhost:8080/api/students

3. READ - Get Student by ID

Endpoint: GET /api/students/{id}

Response (200 OK):

{
  "id": 1,
  "firstName": "John",
  "lastName": "Doe",
  "fullName": "John Doe",
  "email": "john.doe@email.com",
  "age": 20,
  "course": "Computer Science",
  "phoneNumber": "1234567890",
  "dateOfBirth": "2003-05-15",
  "address": "123 Main Street, City, State",
  "isActive": true
}

cURL Command:

curl -X GET http://localhost:8080/api/students/1

4. UPDATE - Update Student

Endpoint: PUT /api/students/{id}

Request Body:

{
  "firstName": "John",
  "lastName": "Doe",
  "email": "john.doe.updated@email.com",
  "age": 21,
  "course": "Computer Science",
  "phoneNumber": "1234567890",
  "dateOfBirth": "2003-05-15",
  "address": "456 Updated Street",
  "isActive": true
}

Response (200 OK):

{
  "id": 1,
  "firstName": "John",
  "lastName": "Doe",
  "fullName": "John Doe",
  "email": "john.doe.updated@email.com",
  "age": 21,
  "course": "Computer Science",
  "phoneNumber": "1234567890",
  "dateOfBirth": "2003-05-15",
  "address": "456 Updated Street",
  "isActive": true
}

cURL Command:

curl -X PUT http://localhost:8080/api/students/1 \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe.updated@email.com",
    "age": 21,
    "course": "Computer Science",
    "phoneNumber": "1234567890",
    "dateOfBirth": "2003-05-15",
    "address": "456 Updated Street",
    "isActive": true
  }'

5. DELETE - Delete Student

Endpoint: DELETE /api/students/{id}

Response: 204 No Content

cURL Command:

curl -X DELETE http://localhost:8080/api/students/1

πŸ” Search Operations

Get Student by Email

curl -X GET http://localhost:8080/api/students/email/john.doe@email.com

Get Students by Course

curl -X GET http://localhost:8080/api/students/course/Computer%20Science

Get Active Students Only

curl -X GET http://localhost:8080/api/students/active

Get Inactive Students Only

curl -X GET http://localhost:8080/api/students/inactive

Search Students by Name

curl -X GET "http://localhost:8080/api/students/search?name=John"

Get Students by Age Range

curl -X GET "http://localhost:8080/api/students/age-range?minAge=18&maxAge=25"

πŸ”§ Utility Operations

Update Student Status (Activate/Deactivate)

curl -X PATCH "http://localhost:8080/api/students/1/status?isActive=false"

Check if Email Exists

curl -X GET "http://localhost:8080/api/students/email-exists?email=john.doe@email.com"

Get Student Count by Course

curl -X GET http://localhost:8080/api/students/course/Computer%20Science/count

Get Active Student Count

curl -X GET http://localhost:8080/api/students/active/count

❌ Error Handling

The application provides detailed error responses for various scenarios:

Validation Error (400 Bad Request)

{
  "timestamp": "2025-11-03T10:30:00",
  "status": 400,
  "error": "Validation Failed",
  "message": "Input validation failed",
  "validationErrors": {
    "firstName": "First name is required",
    "email": "Please provide a valid email address",
    "age": "Age must be at least 15"
  },
  "path": "/api/students"
}

Student Not Found (400 Bad Request)

{
  "timestamp": "2025-11-03T10:30:00",
  "status": 400,
  "error": "Bad Request",
  "message": "Student not found with ID: 999",
  "path": "/api/students"
}

Email Already Exists (400 Bad Request)

{
  "timestamp": "2025-11-03T10:30:00",
  "status": 400,
  "error": "Bad Request",
  "message": "Student with email john.doe@email.com already exists",
  "path": "/api/students"
}

πŸ§ͺ Testing

Run Unit Tests

./mvnw test

Run Specific Test Class

./mvnw test -Dtest=StudentControllerTest

🎯 Learning Objectives Covered

This project demonstrates key concepts for beginners:

  1. Spring Boot Basics - Auto-configuration, annotations, dependency injection
  2. REST API Development - HTTP methods, status codes, request/response handling
  3. Data Persistence - JPA entities, repositories, database operations
  4. Input Validation - Bean validation, custom validators
  5. Error Handling - Global exception handlers, custom error responses
  6. Testing - Unit tests, mocking, test-driven development
  7. Project Structure - Layered architecture, separation of concerns
  8. Best Practices - Code organization, naming conventions, documentation

πŸ“š Key Concepts Explained

1. Layered Architecture

  • Controller Layer - Handles HTTP requests/responses
  • Service Layer - Contains business logic
  • Repository Layer - Handles data access
  • Entity Layer - Represents database tables

2. Data Transfer Objects (DTOs)

  • RequestDTO - Data coming from client
  • ResponseDTO - Data going to client
  • Separates API structure from database structure

3. Dependency Injection

  • Spring automatically provides required dependencies
  • @Autowired, @RequiredArgsConstructor handle injection

4. JPA Repositories

  • Automatic CRUD operations
  • Custom query methods
  • No implementation needed (Spring provides it)

5. Validation Annotations

  • @NotBlank, @NotNull, @Email, @Min, @Max
  • Automatic validation with @Valid

🚧 Future Enhancements

  • Add pagination and sorting
  • Implement security with JWT
  • Add file upload for student photos
  • Create a frontend with React/Angular
  • Add email notifications
  • Implement audit logging
  • Add Docker containerization

🀝 Contributing

Feel free to submit issues and enhancement requests!


πŸ“„ License

This project is for educational purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages