A production-ready, stateless REST API engineered with senior-level backend architecture patterns. Features JWT authentication, role-based access control, dynamic workout tracking, and AI-powered fitness recommendations with strict data integrity and zero-tolerance security standards.
- Core Engineering Features
- Technology Stack
- System Architecture
- Entity Relationship Diagram
- API Endpoints
- Security Architecture
- Quick Start Guide
- Configuration
- Database Migrations
- Testing
- Performance Optimization
- Project Structure
- Contributing
- License
This is not a basic CRUD application. It demonstrates senior-level backend engineering with enterprise-grade architectural patterns and best practices:
- Stateless JWT Authentication: Custom security filter chains using
io.jsonwebtokenfor horizontally scalable, session-less authentication - Role-Based Access Control (RBAC): Fine-grained permission management with
USERandADMINroles - BCrypt Password Hashing: Industry-standard one-way encryption with 10 rounds of salting
- CORS Configuration: Production-ready cross-origin request handling
- Global Exception Handling: Centralized
@RestControllerAdvicepreventing sensitive error information leakage
- Strict Schema Control: Hibernate DDL auto-generation disabled (
ddl-auto=validate) for production safety - Flyway Migrations: Version-controlled database evolution with rollback capabilities
- Optimized Indexing: Composite indexes on
(user_id, activity_id)and unique constraints on email fields - Database-Level Constraints:
CHECKconstraints ensuring data integrity at the storage layer - Connection Pooling: HikariCP for high-performance database connection management
- N-Tier Architecture: Strict separation of concerns (Controller β Service β Repository β Entity)
- DTO Pattern with MapStruct: Compile-time code generation eliminating reflection overhead and preventing data leakage
- Dependency Injection: Constructor-based DI for immutability and testability
- Repository Pattern: Spring Data JPA interfaces with custom query methods
- Transaction Management:
@Transactionalboundaries ensuring ACID properties
- JSON Column Support:
@JdbcTypeCode(SqlTypes.JSON)for flexible, schema-less workout metrics storage - Pagination & Sorting:
Pageablesupport for efficient large dataset handling - Bean Validation: JSR-303/380 annotations for declarative input validation
- OpenAPI 3.0 Documentation: Auto-generated interactive API documentation via Swagger UI
- Custom Exception Hierarchy: Business-specific exceptions (
ResourceNotFoundException,ResourceAlreadyExistsException, etc.)
| Technology | Version | Purpose |
|---|---|---|
| Java | 21 (LTS) | Primary programming language with virtual threads support |
| Spring Boot | 3.4.x | Application framework and dependency injection container |
| Spring Security | 6.x | Authentication, authorization, and security filters |
| Spring Data JPA | 3.x | Data access layer abstraction |
| Hibernate | 6.x | ORM and entity lifecycle management |
| Technology | Version | Purpose |
|---|---|---|
| MySQL | 8.x | Primary relational database |
| Flyway | 10.x | Database version control and migrations |
| HikariCP | 5.x | JDBC connection pooling |
| Technology | Version | Purpose |
|---|---|---|
| jjwt-api | 0.12.x | JWT token generation and validation |
| BCrypt | Built-in | Password hashing algorithm |
| Technology | Version | Purpose |
|---|---|---|
| MapStruct | 1.6.x | Compile-time DTO-Entity mapping |
| Lombok | 1.18.x | Boilerplate code reduction |
| Technology | Version | Purpose |
|---|---|---|
| SpringDoc OpenAPI | 2.x | API documentation and Swagger UI |
| Jakarta Validation | 3.x | Bean validation (JSR-380) |
| Technology | Version | Purpose |
|---|---|---|
| Maven | 3.9.x | Dependency management and build automation |
| Maven Compiler Plugin | 3.13.x | Java compilation with annotation processing |
The application follows a strict N-tier architecture ensuring clean separation of concerns, high testability, and maintainability.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Layer β
β (Web, Mobile, Third-party APIs) β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β HTTP/HTTPS Requests
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Security Filter Chain β
β (JWT Validation, CORS, CSRF Protection) β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Controller Layer β
β β’ HTTP Request Mapping (@RestController) β
β β’ Input Validation (@Valid, @Validated) β
β β’ Response Formatting β
β β’ Exception Handling Trigger β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β DTOs
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Service Layer β
β β’ Business Logic Implementation β
β β’ Transaction Management (@Transactional) β
β β’ Entity β DTO Mapping (MapStruct) β
β β’ Complex Validations β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β Entities
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Repository Layer β
β β’ Data Access Abstraction (Spring Data JPA) β
β β’ Custom Queries (JPQL, Native SQL) β
β β’ Pagination & Sorting β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β SQL Queries
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MySQL Database β
β β’ Relational Data Storage β
β β’ Flyway Schema Migrations β
β β’ Constraints, Indexes, Triggers β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Layer | Responsibilities | Technologies |
|---|---|---|
| Controller | Request routing, validation, response serialization | Spring Web, Jackson, Jakarta Validation |
| Service | Business logic, transactions, orchestration | Spring Core, MapStruct |
| Repository | Database queries, entity management | Spring Data JPA, Hibernate |
| Entity | Domain model, database mapping | JPA, Hibernate |
The database schema is normalized to 3NF to enforce referential integrity, minimize data redundancy, and optimize query performance.
erDiagram
USERS ||--o{ ACTIVITIES : "logs (ON DELETE CASCADE)"
USERS ||--o{ RECOMMENDATIONS : "receives"
ACTIVITIES ||--o{ RECOMMENDATIONS : "generates"
USERS {
BIGINT id PK
VARCHAR(254) email UK "RFC 5321 Compliant"
CHAR(60) password "BCrypt Hash"
VARCHAR(100) first_name
VARCHAR(100) last_name
ENUM role "USER, ADMIN"
TIMESTAMP created_at
TIMESTAMP updated_at
}
ACTIVITIES {
BIGINT id PK
BIGINT user_id FK
ENUM type "RUNNING, CYCLING, WEIGHTLIFTING, SWIMMING..."
INT duration "CHECK > 0 (minutes)"
JSON additional_metrics "Flexible Schema"
DATETIME start_time
TIMESTAMP created_at
}
RECOMMENDATIONS {
BIGINT id PK
BIGINT user_id FK
BIGINT activity_id FK
JSON improvements "Performance enhancement suggestions"
JSON safety "Injury prevention guidance"
TIMESTAMP created_at
}
- Composite Unique Constraint:
(user_id, activity_id)on recommendations table prevents duplicate AI-generated insights - Foreign Key Cascades:
ON DELETE CASCADEfor activities ensures orphaned data is automatically cleaned - Check Constraints: Database-level validation (e.g.,
duration > 0) as a second line of defense - Optimized Data Types:
CHAR(60)for BCrypt hashes,VARCHAR(254)for RFC 5321-compliant emails
Fully documented via OpenAPI 3.0. Once running, visit http://localhost:8080/swagger-ui.html for the interactive Swagger UI.
| Method | Endpoint | Description | Request Body | Response | Access |
|---|---|---|---|---|---|
POST |
/api/auth/register |
Register new user account | RegisterUserDto |
UserResponseDto + JWT |
Public |
POST |
/api/auth/login |
Authenticate and receive JWT token | LoginUserDto |
LoginResponse (JWT) |
Public |
Example Registration Request:
{
"email": "[email protected]",
"password": "SecureP@ssw0rd",
"firstName": "John",
"lastName": "Doe"
}Example Login Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": 3600000
}| Method | Endpoint | Description | Parameters | Response | Access |
|---|---|---|---|---|---|
GET |
/api/users/me |
Get current authenticated user | - | UserResponseDto |
USER, ADMIN |
GET |
/api/users/{id} |
Get user by ID | id (path) |
UserResponseDto |
ADMIN |
GET |
/api/users |
List all users (paginated) | page, size |
Page<UserResponseDto> |
ADMIN |
PUT |
/api/users/{id} |
Update user details | id (path), UpdateUserDto |
UserResponseDto |
USER, ADMIN |
DELETE |
/api/users/{id} |
Delete user account | id (path) |
204 No Content |
ADMIN |
| Method | Endpoint | Description | Parameters | Response | Access |
|---|---|---|---|---|---|
POST |
/api/activities |
Log new fitness activity | ActivityDto |
ActivityResponseDto |
USER, ADMIN |
GET |
/api/activities/user/{userId} |
Get user's activity history | userId, page, size |
Page<ActivityResponseDto> |
USER, ADMIN |
GET |
/api/activities/{id} |
Get activity by ID | id (path) |
ActivityResponseDto |
USER, ADMIN |
PUT |
/api/activities/{id} |
Update activity details | id (path), ActivityDto |
ActivityResponseDto |
USER, ADMIN |
DELETE |
/api/activities/{id} |
Delete activity log | id (path) |
204 No Content |
USER, ADMIN |
Example Activity Request:
{
"type": "RUNNING",
"duration": 45,
"startTime": "2024-03-15T06:30:00Z",
"additionalMetrics": {
"distance": 8.5,
"averagePace": "5:17",
"heartRate": 165,
"calories": 520
}
}| Method | Endpoint | Description | Parameters | Response | Access |
|---|---|---|---|---|---|
POST |
/api/recommendations |
Generate AI-powered fitness recommendations | RecommendationDto |
RecommendationResponseDto |
ADMIN |
GET |
/api/recommendations/activity/{activityId} |
Get recommendations for specific activity | activityId (path) |
RecommendationResponseDto |
USER, ADMIN |
GET |
/api/recommendations/user/{userId} |
Get all user recommendations | userId (path) |
List<RecommendationResponseDto> |
USER, ADMIN |
1. User Registration/Login
βββ Password hashed with BCrypt (10 rounds)
βββ JWT generated with HS256 algorithm
βββ Token contains: { userId, email, role, exp }
2. Authenticated Request
βββ Client sends: Authorization: Bearer <token>
βββ JwtAuthenticationFilter validates token
βββ SecurityContext populated with user details
βββ @PreAuthorize checks role permissions
3. Token Expiration
βββ Default expiry: 24 hours
βββ Refresh mechanism: Re-authenticate
βββ Invalid tokens return 401 Unauthorized
| Feature | Implementation | Benefits |
|---|---|---|
| Password Hashing | BCrypt with strength 10 | Resistant to rainbow table attacks |
| JWT Signing | HMAC-SHA256 | Tamper-proof tokens |
| CORS | Configurable origins | Prevents unauthorized cross-origin requests |
| CSRF Protection | Stateless (disabled for APIs) | JWT-based authentication doesn't require CSRF tokens |
| SQL Injection | Parameterized queries (JPA) | Prevents malicious SQL execution |
| Role-Based Access | @PreAuthorize annotations |
Fine-grained endpoint protection |
| Requirement | Version | Download |
|---|---|---|
| JDK | 21+ | Oracle JDK or OpenJDK |
| Maven | 3.9+ | Apache Maven |
| MySQL | 8.0+ | MySQL Community Server |
| Git | Latest | Git Downloads |
git clone https://github.com/shaikhmahad/fitness-tracker-backend.git
cd fitness-tracker-backendCreate the database:
CREATE DATABASE fitness_tracker CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;Create application-local.yml in src/main/resources/:
spring:
datasource:
url: jdbc:mysql://localhost:3306/fitness_tracker?useSSL=false&serverTimezone=UTC
username: your_mysql_username
password: your_mysql_password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: validate # NEVER use 'update' or 'create-drop' in production
show-sql: true
properties:
hibernate:
format_sql: true
dialect: org.hibernate.dialect.MySQL8Dialect
flyway:
enabled: true
baseline-on-migrate: true
security:
jwt:
secret-key: your-256-bit-secret-key-change-this-in-production
expiration: 86400000 # 24 hours in millisecondsSecurity Warning: Never commit
application-local.ymlto version control. Add it to.gitignore.
export DB_URL="jdbc:mysql://localhost:3306/fitness_tracker"
export DB_USERNAME="your_username"
export DB_PASSWORD="your_password"
export JWT_SECRET="your-secure-secret-key-min-256-bits"
export JWT_EXPIRATION="86400000"MapStruct requires compilation to generate mapper implementations:
mvn clean installmvn spring-boot:runOr run the JAR directly:
java -jar target/fitness-tracker-backend-1.0.0.jarOnce started, visit:
- Swagger UI: http://localhost:8080/swagger-ui.html
- API Docs JSON: http://localhost:8080/v3/api-docs
- Health Check: http://localhost:8080/actuator/health
You should see:
{
"status": "UP"
}| Profile | Purpose | Activation |
|---|---|---|
default |
Development | Active by default |
prod |
Production | --spring.profiles.active=prod |
test |
Integration Testing | Automatically activated during tests |
# Server Configuration
server:
port: 8080
servlet:
context-path: /
# Security
security:
jwt:
secret-key: ${JWT_SECRET:default-secret-for-dev-only}
expiration: ${JWT_EXPIRATION:86400000}
# Database Connection Pooling (HikariCP)
spring:
datasource:
hikari:
maximum-pool-size: 10
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# Flyway Migration
spring:
flyway:
enabled: true
baseline-on-migrate: true
validate-on-migrate: true
# Logging
logging:
level:
root: INFO
dev.shaikhmahad.fitness: DEBUG
org.hibernate.SQL: DEBUGFlyway manages all schema changes with version-controlled SQL scripts located in src/main/resources/db/migration/.
| File | Description | Execution Order |
|---|---|---|
V1__init.sql |
Initial schema creation (users, activities, recommendations) | 1 |
V2__add_missing_recommendation_fields.sql |
Adds JSON columns for improvements and safety tips | 2 |
# Validate migrations
mvn flyway:validate
# View migration status
mvn flyway:info
# Execute pending migrations
mvn flyway:migrate
# Rollback (requires Flyway Teams edition)
mvn flyway:undoβ DO:
- Use descriptive filenames:
V{version}__{description}.sql - Test migrations on a copy of production data
- Keep migrations idempotent where possible
- Version control all migration scripts
β DON'T:
- Modify existing migration files after deployment
- Use Hibernate's
ddl-auto=updatein production - Store sensitive data in migration scripts
# Run all tests
mvn test
# Run with coverage report
mvn test jacoco:report
# Run specific test class
mvn test -Dtest=UserServiceImplTest
# Run integration tests only
mvn verify -P integration-testssrc/test/java/dev/shaikhmahad/fitness/
βββ controllers/ # Controller layer tests (MockMvc)
βββ services/ # Service layer tests (Mockito)
βββ repositories/ # Repository tests (DataJpaTest)
βββ integration/ # End-to-end integration tests
- Composite Indexes:
(user_id, activity_id)for recommendation lookups - Connection Pooling: HikariCP with optimized pool sizes
- Query Optimization: N+1 query prevention with
@EntityGraph - Pagination: All list endpoints return
Page<T>to limit result sets
- DTO Mapping: Compile-time MapStruct (zero reflection overhead)
- Lazy Loading: Strategic use of
FetchType.LAZYfor collections - Caching: Spring Cache abstraction ready for Redis integration
- Async Processing:
@Asyncsupport for non-blocking operations
fitness-tracker-backend/
β
βββ src/main/java/dev/shaikhmahad/fitness/
β βββ config/
β β βββ ApplicationConfiguration.java # Bean definitions
β β βββ JwtAuthenticationFilter.java # JWT validation filter
β β βββ SecurityConfiguration.java # Security chains
β β
β βββ controllers/
β β βββ AuthenticationController.java # /api/auth/*
β β βββ UserController.java # /api/users/*
β β βββ ActivityController.java # /api/activities/*
β β βββ RecommendationController.java # /api/recommendations/*
β β
β βββ dto/
β β βββ request/ # Inbound DTOs
β β β βββ RegisterUserDto.java
β β β βββ LoginUserDto.java
β β β βββ ActivityDto.java
β β βββ response/ # Outbound DTOs
β β βββ UserResponseDto.java
β β βββ ActivityResponseDto.java
β β
β βββ entities/
β β βββ User.java # JPA entity
β β βββ Activity.java
β β βββ Recommendation.java
β β
β βββ enums/
β β βββ UserRole.java # USER, ADMIN
β β βββ ActivityType.java # RUNNING, CYCLING, etc.
β β
β βββ exceptions/
β β βββ GlobalExceptionHandler.java # @RestControllerAdvice
β β βββ ResourceNotFoundException.java
β β βββ ResourceAlreadyExistsException.java
β β
β βββ mappers/
β β βββ UserMapper.java # MapStruct interface
β β βββ ActivityMapper.java
β β
β βββ repositories/
β β βββ UserRepository.java # Spring Data JPA
β β βββ ActivityRepository.java
β β βββ RecommendationRepository.java
β β
β βββ services/
β β βββ AuthenticationService.java
β β βββ JwtService.java
β β βββ UserService.java
β β βββ impl/ # Service implementations
β β βββ UserServiceImpl.java
β β βββ ActivityServiceImpl.java
β β
β βββ FitnessTrackerApplication.java # Spring Boot entry point
β
βββ src/main/resources/
β βββ db/migration/ # Flyway SQL scripts
β β βββ V1__init.sql
β β βββ V2__add_missing_recommendation_fields.sql
β βββ application.yml # Main configuration
β βββ application-prod.yml # Production overrides
β
βββ src/test/java/ # Unit & integration tests
βββ pom.xml # Maven dependencies
βββ README.md # This file
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch
git checkout -b feature/amazing-feature
- Make your changes following the coding standards
- Write tests for new functionality
- Commit with conventional commits
git commit -m "feat: add amazing feature" - Push to your fork
git push origin feature/amazing-feature
- Open a Pull Request
- Follow Java naming conventions
- Use meaningful variable/method names
- Write JavaDoc for public methods
- Maintain test coverage above 80%
- Use Lombok to reduce boilerplate
- Follow SOLID principles
feat: Add new feature
fix: Bug fix
docs: Documentation changes
style: Code formatting
refactor: Code restructuring
test: Add tests
chore: Build/config changes
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 Shaikh Mahad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Spring Team - For the excellent Spring Framework and Spring Boot
- Hibernate Team - For robust ORM capabilities
- MapStruct Contributors - For compile-time DTO mapping
- Flyway - For database version control
- JWT.io - For JWT implementation resources
Shaikh Mahad Backend Engineer | Java & Spring Boot Specialist
Have questions or suggestions? Feel free to reach out!
π§ Email: [email protected] πΌ LinkedIn: linkedin.com/in/codewithmahad π Portfolio: shaikhmahad.vercel.app
If you found this project helpful or learned something new, please consider giving it a β!