0% found this document useful (0 votes)
19 views21 pages

SPB Guide

SPRING BOOT DETAILED GUIDE FOR MERN STACK DEVELOPERS

Uploaded by

NR VY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views21 pages

SPB Guide

SPRING BOOT DETAILED GUIDE FOR MERN STACK DEVELOPERS

Uploaded by

NR VY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

From MERN Stack to Spring Boot: A Complete

Guide
Spring Boot Development Expert

2025-10-03

Contents
1 Introduction 3

2 High-Level Overview: MERN vs Spring Boot 3

3 Core Architecture: MVC Pattern 3


3.1 What is MVC? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.2 The MVC Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.3 MVC in MERN Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

4 Understanding the Controller Layer 4


4.1 What is a Controller? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 MERN Example (Express.js) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.3 Spring Boot Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.4 Key Controller Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

5 Understanding the Service Layer 5


5.1 What is a Service Class? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.2 Why Separate Service Layer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.3 Spring Boot Service Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.4 Service Layer Responsibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

6 Understanding the Repository Layer 7


6.1 What is a Repository? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.2 MERN Example (Mongoose) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.3 Spring Boot Repository Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.4 Repository Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.5 Query Method Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . 8

7 Understanding the Entity/Model Layer 8


7.1 What is an Entity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.2 MERN Example (Mongoose Schema) . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.3 Spring Boot Entity Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7.4 Entity Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

8 Complete Flow Comparison 11


8.1 MERN Stack Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8.2 Spring Boot Layered Architecture Flow . . . . . . . . . . . . . . . . . . . . . . . 11
8.2.1 Controller Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8.2.2 Service Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1
8.2.3 Repository Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.2.4 Entity (Model) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

9 Key Differences: MERN vs Spring Boot 12

10 Learning Roadmap 13
10.1 Phase 1: Java Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.2 Phase 2: Spring Boot Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
10.3 Phase 3: Building REST APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.4 Phase 4: Database Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.5 Phase 5: Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

11 Complete CRUD Example 14


11.1 MERN Stack Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2 Spring Boot Layered Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 15
11.2.1 Entity Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
11.2.2 Repository Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
11.2.3 Service Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
11.2.4 Controller Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.3 Exception Handling (Optional but Recommended) . . . . . . . . . . . . . . . . . 18

12 Configuration Files 19
12.1 application.properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

13 Summary 19

14 Next Steps 20

2
1 Introduction
Welcome to Spring Boot! If you’re coming from the MERN Stack (MongoDB, Express, React,
Node.js), you already have a solid foundation in backend development. Spring Boot will feel
familiar in many ways, but with some key differences.
This guide will help you understand the core concepts of Spring Boot by drawing parallels
to what you already know from MERN development.

2 High-Level Overview: MERN vs Spring Boot

MERN Stack Spring Boot Purpose


Express.js Routes Controller Handle HTTP requests
Business Logic in Service Class Business logic layer
Routes/Services
Mongoose Models/- Repository Data access layer
MongoDB
MVC Pattern (if used) MVC Architecture Architectural pattern
Node.js + Express Spring Boot Framework/Runtime
JavaScript/TypeScript Java Programming Language

Table 1: Comparison: MERN Stack vs Spring Boot

3 Core Architecture: MVC Pattern


3.1 What is MVC?
MVC (Model-View-Controller) is an architectural pattern that separates your application
into three main components. This separation provides better organization, maintainability, and
testability.

3
3.2 The MVC Flow
Application Flow

CLIENT (Browser/App)
↓ HTTP Request
CONTROLLER LAYER
(Handles requests, calls services)
@RestController / @Controller

SERVICE LAYER
(Business logic, validation)
@Service

REPOSITORY LAYER
(Database operations)
@Repository / JPA Repository

DATABASE (MySQL, PostgreSQL)

3.3 MVC in MERN Terms


• View — React (frontend)

• Controller — Express routes

• Model — Mongoose schemas + MongoDB

4 Understanding the Controller Layer


4.1 What is a Controller?
The Controller is the entry point for HTTP requests. It receives requests from clients, calls
appropriate services, and returns responses.
MERN Equivalent: Express route handlers

4.2 MERN Example (Express.js)

1 // Express route
2 app . get ( ’/ api / users /: id ’ , async ( req , res ) = > {
3 try {
4 const user = await User . findById ( req . params . id ) ;
5 res . json ( user ) ;
6 } catch ( error ) {
7 res . status (500) . json ({ error : error . message }) ;
8 }
9 }) ;

4.3 Spring Boot Example

1 @RestController
2 @RequestMapping ( " / api / users " )
3 public class UserController {

4
4
5 @Autowired
6 private UserService userService ;
7
8 @GetMapping ( " /{ id } " )
9 public ResponseEntity < User > getUser ( @PathVariable Long id ) {
10 User user = userService . getUserById ( id ) ;
11 return ResponseEntity . ok ( user ) ;
12 }
13 }

4.4 Key Controller Annotations

Annotation Description
@RestController Marks class as REST API controller (returns JSON data)
@Controller Marks class as web controller (returns HTML views)
@RequestMapping Defines base URL path for all methods in controller
@GetMapping Maps HTTP GET requests to handler method
@PostMapping Maps HTTP POST requests to handler method
@PutMapping Maps HTTP PUT requests to handler method
@DeleteMapping Maps HTTP DELETE requests to handler method
@PathVariable Extracts values from URL path (like req.params in Ex-
press)
@RequestParam Extracts query parameters (like req.query in Express)
@RequestBody Extracts request body (like req.body in Express)
Table 2: Spring Boot Controller Annotations

5 Understanding the Service Layer


5.1 What is a Service Class?
The Service layer contains your business logic. It sits between the Controller and Repository,
processing data, applying validation, and implementing business rules.
MERN Equivalent: Service functions or business logic you write separately from routes

5
5.2 Why Separate Service Layer?
Benefits of Service Layer

• Separation of Concerns — Controllers handle HTTP, Services handle logic

• Reusability — Multiple controllers can use the same service

• Testability — Easy to test business logic independently

• Clean Code — Keeps controllers thin and focused

• Maintainability — Business rules in one centralized location

5.3 Spring Boot Service Example

1 @Service
2 public class UserService {
3
4 @Autowired
5 private UserRepository userRepository ;
6
7 public User getUserById ( Long id ) {
8 return userRepository . findById ( id )
9 . orElseThrow (() -> new U s e r N o t F o u n d E x c e p t i o n ( " User ␣ not ␣
found " ) ) ;
10 }
11
12 public User createUser ( User user ) {
13 // Business logic : validate email
14 if (! isValidEmail ( user . getEmail () ) ) {
15 throw new I n v a l i d E m a i l E x c e p t i o n ( " Invalid ␣ email ␣ format " ) ;
16 }
17 return userRepository . save ( user ) ;
18 }
19
20 public List < User > ge tAllAc tiveUs ers () {
21 // Business logic : filter active users
22 return userRepository . findAll ()
23 . stream ()
24 . filter ( User :: isActive )
25 . collect ( Collectors . toList () ) ;
26 }
27

28 private boolean isValidEmail ( String email ) {


29 // Validation logic
30 return email . contains ( " @ " ) ;
31 }
32 }

5.4 Service Layer Responsibilities


• Business Logic — Core application logic and rules

• Data Validation — Validate input before processing

• Data Transformation — Convert between DTOs and entities

6
• Transaction Management — Manage database transactions

• Exception Handling — Handle business-level exceptions

• Orchestration — Coordinate between multiple repositories

Important Note

Service classes should NOT contain any HTTP-related code (no request/response han-
dling). They should be independent of the web layer.

6 Understanding the Repository Layer


6.1 What is a Repository?
The Repository layer handles all database operations (CRUD — Create, Read, Update,
Delete). It abstracts the database access logic.
MERN Equivalent: Mongoose models and database queries

6.2 MERN Example (Mongoose)

1 // Mongoose model
2 const User = mongoose . model ( ’ User ’ , userSchema ) ;
3
4 // Database operations
5 const user = await User . findById ( id ) ;
6 const users = await User . find ({ active : true }) ;
7 await User . create ({ name : ’ John ’ , email : ’ john@example . com ’ }) ;
8 await User . fi ndById AndUpd ate ( id , { name : ’ Jane ’ }) ;
9 await User . fi ndById AndDel ete ( id ) ;

6.3 Spring Boot Repository Example

1 @Repository
2 public interface UserRepository extends JpaRepository < User , Long > {
3

4 // Spring Data JPA provides these automatically :


5 // - save ()
6 // - findById ()
7 // - findAll ()
8 // - deleteById ()
9 // - count ()
10 // - existsById ()
11
12 // Custom query methods
13 List < User > findByEmail ( String email ) ;
14 List < User > findByActiveTrue () ;
15 List < User > f i n d B y A g e G r e a t e r T h a n ( int age ) ;
16 List < User > f i n d B y N a m e C o n t a i n i n g ( String name ) ;
17
18 @Query ( " SELECT ␣ u ␣ FROM ␣ User ␣ u ␣ WHERE ␣ u . name ␣ LIKE ␣ %: name % " )
19 List < User > searchByName ( @Param ( " name " ) String name ) ;
20 }

7
6.4 Repository Features
JpaRepository Power Features

• Built-in CRUD Methods — No need to write basic operations

• Query Method Generation — Spring generates queries from method names

• Custom Queries — Use @Query for complex operations

• Pagination Support — Built-in pagination and sorting

• Type Safety — Compile-time type checking

• No SQL Required — For most common operations

6.5 Query Method Naming Conventions

Method Name Generated Query


findByName(String name) SELECT * FROM user WHERE name = ?
findByEmailAndActive(...) SELECT * WHERE email = ? AND active = ?
findByAgeGreaterThan(int SELECT * WHERE age > ?
age)
findByNameContaining(String SELECT * WHERE name LIKE %?%
n)
findByActiveTrue() SELECT * WHERE active = true
findByOrderByNameAsc() SELECT * ORDER BY name ASC
countByActive(boolean SELECT COUNT(*) WHERE active = ?
active)
deleteByEmail(String email) DELETE FROM user WHERE email = ?
Table 3: Spring Data JPA Query Method Examples

7 Understanding the Entity/Model Layer


7.1 What is an Entity?
The Entity represents your database table structure. It’s like a Mongoose schema but for
relational databases.
MERN Equivalent: Mongoose Schema

7.2 MERN Example (Mongoose Schema)

1 const userSchema = new mongoose . Schema ({


2 name : { type : String , required : true } ,
3 email : { type : String , required : true , unique : true } ,
4 age : { type : Number } ,
5 active : { type : Boolean , default : true } ,
6 createdAt : { type : Date , default : Date . now }
7 }) ;

8
8
9 const User = mongoose . model ( ’ User ’ , userSchema ) ;

7.3 Spring Boot Entity Example

1 @Entity
2 @Table ( name = " users " )
3 public class User {
4
5 @Id
6 @GeneratedValue ( strategy = GenerationType . IDENTITY )
7 private Long id ;
8
9 @Column ( nullable = false )
10 private String name ;
11
12 @Column ( nullable = false , unique = true )
13 private String email ;
14
15 private Integer age ;
16
17 @Column ( columnDefinition = " boolean ␣ default ␣ true " )
18 private Boolean active ;
19

20 @CreatedDate
21 private LocalDateTime createdAt ;
22
23 // Default Constructor ( Required by JPA )
24 public User () {}
25

26 // Parameterized Constructor
27 public User ( String name , String email , Integer age ) {
28 this . name = name ;
29 this . email = email ;
30 this . age = age ;
31 }
32
33 // Getters and Setters
34 public Long getId () {
35 return id ;
36 }
37

38 public void setId ( Long id ) {


39 this . id = id ;
40 }
41
42 public String getName () {
43 return name ;
44 }
45
46 public void setName ( String name ) {
47 this . name = name ;
48 }
49

50 public String getEmail () {


51 return email ;
52 }

9
53
54 public void setEmail ( String email ) {
55 this . email = email ;
56 }
57
58 public Integer getAge () {
59 return age ;
60 }
61

62 public void setAge ( Integer age ) {


63 this . age = age ;
64 }
65
66 public Boolean getActive () {
67 return active ;
68 }
69
70 public void setActive ( Boolean active ) {
71 this . active = active ;
72 }
73

74 public LocalDateTime getCreatedAt () {


75 return createdAt ;
76 }
77
78 public void setCreatedAt ( LocalDateTime createdAt ) {
79 this . createdAt = createdAt ;
80 }
81 }

7.4 Entity Annotations

Annotation Description
@Entity Marks the class as a JPA entity (database table)
@Table(name = "...") Specifies the table name in database
@Id Marks the primary key field
@GeneratedValue Auto-generates ID values (auto-increment)
@Column Defines column properties (nullable, unique, etc.)
@Transient Field not persisted to database
@CreatedDate Automatically sets creation timestamp
@LastModifiedDate Automatically updates modification timestamp
@OneToMany One-to-many relationship
@ManyToOne Many-to-one relationship
@ManyToMany Many-to-many relationship
Table 4: JPA Entity Annotations

10
Important Requirement

JPA entities MUST have:

• A default no-argument constructor

• Getters and setters for all fields

• A field marked with @Id

8 Complete Flow Comparison


8.1 MERN Stack Flow

1 // 1. Route Handler ( Express ) - Everything in one place


2 app . post ( ’/ api / users ’ , async ( req , res ) = > {
3 try {
4 // 2. Business logic ( inline )
5 const { name , email } = req . body ;
6 if (! email . includes ( ’@ ’) ) {
7 return res . status (400) . json ({ error : ’ Invalid email ’ }) ;
8 }
9
10 // 3. Database operation ( Mongoose )
11 const user = await User . create ({ name , email }) ;
12

13 // 4. Response
14 res . status (201) . json ( user ) ;
15 } catch ( error ) {
16 res . status (500) . json ({ error : error . message }) ;
17 }
18 }) ;

8.2 Spring Boot Layered Architecture Flow


8.2.1 Controller Layer

1 @RestController
2 @RequestMapping ( " / api / users " )
3 public class UserController {
4
5 @Autowired
6 private UserService userService ;
7
8 @PostMapping
9 public ResponseEntity < User > createUser ( @RequestBody UserDTO userDTO
) {
10 User user = userService . createUser ( userDTO ) ;
11 return ResponseEntity . status ( HttpStatus . CREATED ) . body ( user ) ;
12 }
13 }

8.2.2 Service Layer

11
1 @Service
2 public class UserService {
3
4 @Autowired
5 private UserRepository userRepository ;
6
7 public User createUser ( UserDTO userDTO ) {
8 // Business logic
9 if (! isValidEmail ( userDTO . getEmail () ) ) {
10 throw new I n v a l i d E m a i l E x c e p t i o n ( " Invalid ␣ email " ) ;
11 }
12
13 User user = new User ( userDTO . getName () , userDTO . getEmail () ) ;
14 return userRepository . save ( user ) ;
15 }
16
17 private boolean isValidEmail ( String email ) {
18 return email . contains ( " @ " ) ;
19 }
20 }

8.2.3 Repository Layer

1 @Repository
2 public interface UserRepository extends JpaRepository < User , Long > {
3 // Spring provides save () , findById () , etc . automatically
4 }

8.2.4 Entity (Model)

1 @Entity
2 public class User {
3 @Id
4 @GeneratedValue ( strategy = GenerationType . IDENTITY )
5 private Long id ;
6 private String name ;
7 private String email ;
8
9 // Constructors , getters , setters ...
10 }

9 Key Differences: MERN vs Spring Boot

Aspect MERN (Express + Mon- Spring Boot


goose)
Language JavaScript/TypeScript Java
Architecture Often routes + logic mixed Strict layered architecture
Database MongoDB (NoSQL) MySQL, PostgreSQL (SQL)
ORM Mongoose JPA/Hibernate

12
Aspect MERN (Express + Mon- Spring Boot
goose)

Typing Dynamic (or TypeScript op- Static (strongly typed)


tional)
Dependency Man- npm/yarn Maven/Gradle
agement
Configuration Code-based Annotation-based + properties
files
Boilerplate Less boilerplate More boilerplate (getters/set-
ters)
Object Creation Manual with new keyword Automatic with IoC Container
Async Handling async/await Synchronous by default
Learning Curve Easier for beginners Steeper but more structured
Table 5: Comprehensive Comparison: MERN vs Spring Boot

10 Learning Roadmap
10.1 Phase 1: Java Fundamentals
Java Prerequisites

Before diving into Spring Boot, ensure you understand:

• Java syntax and basic concepts

• Object-Oriented Programming (OOP)

• Classes, objects, inheritance, polymorphism

• Interfaces and abstract classes

• Collections (List, Set, Map)

• Exception handling (try-catch-finally)

• Lambdas and Stream API

• Generics

10.2 Phase 2: Spring Boot Basics


• IoC (Inversion of Control) and Dependency Injection

• Spring Boot project structure and initialization

• Core annotations: @SpringBootApplication, @Component, @Service, @Repository

• Configuration with application.properties or application.yml

• Bean lifecycle and scopes

13
10.3 Phase 3: Building REST APIs
• @RestController and @RequestMapping

• HTTP method annotations: @GetMapping, @PostMapping, etc.

• Request parameter handling: @PathVariable, @RequestParam, @RequestBody

• ResponseEntity for custom HTTP responses

• DTOs (Data Transfer Objects) and mapping

• Content negotiation (JSON, XML)

10.4 Phase 4: Database Integration


• JPA (Java Persistence API) fundamentals

• Entity mapping: @Entity, @Id, @GeneratedValue

• JpaRepository interface and custom query methods

• Database relationships: @OneToMany, @ManyToOne, @ManyToMany

• Connecting to MySQL/PostgreSQL

• Database migrations with Flyway or Liquibase

10.5 Phase 5: Advanced Topics


• Exception handling with @ControllerAdvice and @ExceptionHandler

• Validation with @Valid, @NotNull, @Size, etc.

• Spring Security (authentication and authorization)

• Testing with JUnit 5 and Mockito

• Logging with SLF4J and Logback

• API documentation with Swagger/OpenAPI

• Actuator for monitoring and health checks

11 Complete CRUD Example


Let’s build a complete User Management API comparing both approaches.

11.1 MERN Stack Implementation

1 // Model
2 const userSchema = new mongoose . Schema ({
3 name : String ,
4 email : String
5 }) ;
6 const User = mongoose . model ( ’ User ’ , userSchema ) ;
7
8 // Routes - Everything in one file
9 app . get ( ’/ api / users ’ , async ( req , res ) = > {

14
10 const users = await User . find () ;
11 res . json ( users ) ;
12 }) ;
13
14 app . post ( ’/ api / users ’ , async ( req , res ) = > {
15 const user = await User . create ( req . body ) ;
16 res . status (201) . json ( user ) ;
17 }) ;
18

19 app . get ( ’/ api / users /: id ’ , async ( req , res ) = > {


20 const user = await User . findById ( req . params . id ) ;
21 res . json ( user ) ;
22 }) ;
23
24 app . put ( ’/ api / users /: id ’ , async ( req , res ) = > {
25 const user = await User . fi ndById AndUpd ate (
26 req . params . id ,
27 req . body ,
28 { new : true }
29 );
30 res . json ( user ) ;
31 }) ;
32
33 app . delete ( ’/ api / users /: id ’ , async ( req , res ) = > {
34 await User . fin dByIdA ndDel ete ( req . params . id ) ;
35 res . status (204) . send () ;
36 }) ;

11.2 Spring Boot Layered Implementation


11.2.1 Entity Layer

1 @Entity
2 @Table ( name = " users " )
3 public class User {
4
5 @Id
6 @GeneratedValue ( strategy = GenerationType . IDENTITY )
7 private Long id ;
8

9 @Column ( nullable = false )


10 private String name ;
11
12 @Column ( nullable = false , unique = true )
13 private String email ;
14

15 // Default Constructor
16 public User () {}
17
18 // Parameterized Constructor
19 public User ( String name , String email ) {
20 this . name = name ;
21 this . email = email ;
22 }
23
24 // Getters and Setters
25 public Long getId () { return id ; }

15
26 public void setId ( Long id ) { this . id = id ; }
27
28 public String getName () { return name ; }
29 public void setName ( String name ) { this . name = name ; }
30
31 public String getEmail () { return email ; }
32 public void setEmail ( String email ) { this . email = email ; }
33 }

11.2.2 Repository Layer

1 @Repository
2 public interface UserRepository extends JpaRepository < User , Long > {
3 // JpaRepository provides all CRUD methods automatically :
4 // - save ( User user )
5 // - findById ( Long id )
6 // - findAll ()
7 // - deleteById ( Long id )
8 // - count ()
9 // - existsById ( Long id )
10
11 // Custom query methods
12 Optional < User > findByEmail ( String email ) ;
13 }

11.2.3 Service Layer

1 @Service
2 public class UserService {
3
4 @Autowired
5 private UserRepository userRepository ;
6
7 public List < User > getAllUsers () {
8 return userRepository . findAll () ;
9 }
10
11 public User getUserById ( Long id ) {
12 return userRepository . findById ( id )
13 . orElseThrow (() -> new R e s o u r c e N o t F o u n d E x c e p t i o n (
14 " User ␣ not ␣ found ␣ with ␣ id : ␣ " + id
15 ));
16 }
17
18 public User createUser ( User user ) {
19 // Business logic : Check if email already exists
20 if ( userRepository . findByEmail ( user . getEmail () ) . isPresent () ) {
21 throw new D u p l i c a t e R e s o u r c e E x c e p t i o n (
22 " User ␣ with ␣ email ␣ " + user . getEmail () + " ␣ already ␣ exists
"
23 );
24 }
25 return userRepository . save ( user ) ;
26 }
27
28 public User updateUser ( Long id , User userDetails ) {

16
29 User user = getUserById ( id ) ;
30 user . setName ( userDetails . getName () ) ;
31 user . setEmail ( userDetails . getEmail () ) ;
32 return userRepository . save ( user ) ;
33 }
34
35 public void deleteUser ( Long id ) {
36 if (! userRepository . existsById ( id ) ) {
37 throw new R e s o u r c e N o t F o u n d E x c e p t i o n (
38 " User ␣ not ␣ found ␣ with ␣ id : ␣ " + id
39 );
40 }
41 userRepository . deleteById ( id ) ;
42 }
43 }

11.2.4 Controller Layer

1 @RestController
2 @RequestMapping ( " / api / users " )
3 public class UserController {
4
5 @Autowired
6 private UserService userService ;
7
8 // GET / api / users - Get all users
9 @GetMapping
10 public ResponseEntity < List < User > > getAllUsers () {
11 List < User > users = userService . getAllUsers () ;
12 return ResponseEntity . ok ( users ) ;
13 }
14
15 // GET / api / users /{ id } - Get user by ID
16 @GetMapping ( " /{ id } " )
17 public ResponseEntity < User > getUserById ( @PathVariable Long id ) {
18 User user = userService . getUserById ( id ) ;
19 return ResponseEntity . ok ( user ) ;
20 }
21

22 // POST / api / users - Create new user


23 @PostMapping
24 public ResponseEntity < User > createUser ( @RequestBody User user ) {
25 User createdUser = userService . createUser ( user ) ;
26 return ResponseEntity
27 . status ( HttpStatus . CREATED )
28 . body ( createdUser ) ;
29 }
30
31 // PUT / api / users /{ id } - Update user
32 @PutMapping ( " /{ id } " )
33 public ResponseEntity < User > updateUser (
34 @PathVariable Long id ,
35 @RequestBody User user ) {
36 User updatedUser = userService . updateUser ( id , user ) ;
37 return ResponseEntity . ok ( updatedUser ) ;
38 }
39

17
40 // DELETE / api / users /{ id } - Delete user
41 @DeleteMapping ( " /{ id } " )
42 public ResponseEntity < Void > deleteUser ( @PathVariable Long id ) {
43 userService . deleteUser ( id ) ;
44 return ResponseEntity . noContent () . build () ;
45 }
46 }

11.3 Exception Handling (Optional but Recommended)

1 @C ontrol lerAdv ice


2 public class G l o b a l E x c e p t i o n H a n d l e r {
3
4 @E xcepti onHand ler ( R e s o u r c e N o t F o u n d E x c e p t i o n . class )
5 public ResponseEntity < ErrorResponse > h a n d l e R e s o u r c e N o t F o u n d (
6 R e s o u r c e N o t F o u n d E x c e p t i o n ex ) {
7 ErrorResponse error = new ErrorResponse (
8 HttpStatus . NOT_FOUND . value () ,
9 ex . getMessage () ,
10 LocalDateTime . now ()
11 );
12 return ResponseEntity
13 . status ( HttpStatus . NOT_FOUND )
14 . body ( error ) ;
15 }
16
17 @Ex ceptio nHandl er ( D u p l i c a t e R e s o u r c e E x c e p t i o n . class )
18 public ResponseEntity < ErrorResponse > h a n d l e D u p l i c a t e R e s o u r c e (
19 D u p l i c a t e R e s o u r c e E x c e p t i o n ex ) {
20 ErrorResponse error = new ErrorResponse (
21 HttpStatus . CONFLICT . value () ,
22 ex . getMessage () ,
23 LocalDateTime . now ()
24 );
25 return ResponseEntity
26 . status ( HttpStatus . CONFLICT )
27 . body ( error ) ;
28 }
29
30 @Ex ceptio nHandl er ( Exception . class )
31 public ResponseEntity < ErrorResponse > h a n d l e G l o b a l E x c e p t i o n (
32 Exception ex ) {
33 ErrorResponse error = new ErrorResponse (
34 HttpStatus . I N T E R N A L _ S E R V E R _ E R R O R . value () ,
35 " An ␣ error ␣ occurred : ␣ " + ex . getMessage () ,
36 LocalDateTime . now ()
37 );
38 return ResponseEntity
39 . status ( HttpStatus . I N T E R N A L _ S E R V E R _ E R R O R )
40 . body ( error ) ;
41 }
42 }

18
12 Configuration Files
12.1 application.properties

# Server Configuration
s e r v e r . p o r t =8080

# Database C o n f i g u r a t i o n (MySQL)
s p r i n g . d a t a s o u r c e . u r l=j d b c : mysql : / / l o c a l h o s t : 3 3 0 6 / u s e r d b
s p r i n g . d a t a s o u r c e . username=r o o t
s p r i n g . d a t a s o u r c e . password=yourpassword

# JPA C o n f i g u r a t i o n
s p r i n g . j p a . h i b e r n a t e . ddl−auto=update
s p r i n g . j p a . show−s q l=t r u e
s p r i n g . j p a . p r o p e r t i e s . h i b e r n a t e . f o r m a t s q l=t r u e

# Logging
l o g g i n g . l e v e l . o r g . s p r i n g f r a m e w o r k=INFO
l o g g i n g . l e v e l . com . yourpackage=DEBUG

13 Summary
Key Takeaways

• Controller is equivalent to Express routes — handles HTTP requests and re-


sponses

• Service contains business logic — validation, data processing, business rules

• Repository is like Mongoose models — handles database operations

• Entity is equivalent to Mongoose schema — defines database structure

• MVC Architecture provides separation of concerns and better organization

• Spring Boot uses layered architecture — strict separation between layers

• JpaRepository provides built-in CRUD methods — no need to write basic queries

• Annotations drive configuration — @RestController, @Service,


@Repository, @Entity

• Java is strongly typed — more verbose but safer than JavaScript

• IoC Container manages objects — no manual object creation with new keyword

• Dependency Injection makes testing easier and code more maintainable

• More boilerplate in Spring Boot but better structure and scalability

19
Learning Path Summary

1. Master Java fundamentals (OOP, collections, exceptions)

2. Understand IoC and Dependency Injection concepts

3. Learn Spring Boot project structure and configuration

4. Build REST APIs with Controllers

5. Implement business logic in Services

6. Work with JPA and Repositories for database access

7. Add validation and exception handling

8. Explore Spring Security for authentication

9. Write tests with JUnit and Mockito

10. Document APIs with Swagger/OpenAPI

14 Next Steps
Now that you understand the core concepts, here are your next steps:

1. Practice Building APIs — Create simple CRUD applications

2. Learn Spring Data JPA — Master database operations

3. Explore Spring Security — Implement authentication and authorization

4. Study Exception Handling — Use @ControllerAdvice for global error handling

5. Write Tests — Learn JUnit and Mockito for unit testing

6. Build Real Projects — Apply concepts in actual applications

7. Read Documentation — Spring Boot official docs are excellent

20
Remember
Coming from MERN Stack, you already understand:

• REST API design principles

• HTTP methods and status codes

• Database operations (CRUD)

• Client-server architecture

• API testing and debugging

These skills transfer directly to Spring Boot. The main differences are:

• Language (Java vs JavaScript)

• Architecture (layered vs routes-based)

• Type system (static vs dynamic)

• Configuration approach (annotations vs code)

21

You might also like