<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Mohammed Quasim D A</title>
    <description>The latest articles on Forem by Mohammed Quasim D A (@mohammedquasimda).</description>
    <link>https://forem.com/mohammedquasimda</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3176975%2F8e404247-015a-4ad2-bdb1-be0a9e2d63c6.png</url>
      <title>Forem: Mohammed Quasim D A</title>
      <link>https://forem.com/mohammedquasimda</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mohammedquasimda"/>
    <language>en</language>
    <item>
      <title>Beginner’s Guide to Exception Handling in Spring Boot</title>
      <dc:creator>Mohammed Quasim D A</dc:creator>
      <pubDate>Fri, 23 May 2025 02:33:32 +0000</pubDate>
      <link>https://forem.com/mohammedquasimda/beginners-guide-to-exception-handling-in-spring-boot-mo7</link>
      <guid>https://forem.com/mohammedquasimda/beginners-guide-to-exception-handling-in-spring-boot-mo7</guid>
      <description>&lt;p&gt;This is continuation of Building a Student Management API with Spring Boot: A Step-by-Step Guide &lt;/p&gt;

&lt;p&gt;github:&lt;a href="https://github.com/mohammedQuasimDA/smart-campus" rel="noopener noreferrer"&gt;https://github.com/mohammedQuasimDA/smart-campus&lt;/a&gt; &lt;br&gt;
If you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    Have doubts about any part of this guide
    Find something confusing or unclear
    Notice typos/errors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please reach out in the comments/DMs—I’d be delighted to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    Clarify concepts
    Fix mistakes promptly
    Improve this resource for everyone
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your feedback helps make this article more accurate and helpful for future readers! &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Create an dir exception&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Exception Handling Matters
&lt;/h2&gt;

&lt;p&gt;When building REST APIs, you want to return meaningful and consistent error messages when something goes wrong (e.g., bad input, not found, duplicates). That’s where Spring Boot’s exception handling with @ControllerAdvice and @ExceptionHandler comes in&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Define Custom Exceptions
&lt;/h2&gt;

&lt;p&gt;Create custom exceptions for specific error cases. These extend RuntimeException&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Duplicate roll number
public class DuplicateRollNumberException extends RuntimeException {
    public DuplicateRollNumberException(String message) {
        super(message);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Invalid department code
public class InvalidDepartmentCodeException extends RuntimeException {
    public InvalidDepartmentCodeException(String code) {
        super("Invalid department code: " + code);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Student not found
public class StudentNotFoundException extends RuntimeException {
    public StudentNotFoundException(String rollNumber) {
        super("Student not found with roll number: " + rollNumber);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Create a Standard Error Response Object
&lt;/h2&gt;

&lt;p&gt;We want every error to return a consistent JSON structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ErrorResponse {
    private LocalDateTime timestamp;
    private int status;
    private String error;
    private String message;
    private String path;
    private Map&amp;lt;String, String&amp;gt; details; // Optional: for field validation errors

    // Constructor for general errors
    public ErrorResponse(HttpStatus status, String message) {
        this.timestamp = LocalDateTime.now();
        this.status = status.value();
        this.error = status.getReasonPhrase();
        this.message = message;
    }

    // Constructor for validation errors
    public ErrorResponse(HttpStatus status, String message, Map&amp;lt;String, String&amp;gt; details) {
        this(status, message);
        this.details = details;
    }

    // Getters and setters...
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Build a Global Exception Handler with @ControllerAdvice
&lt;/h2&gt;

&lt;p&gt;This class handles all exceptions in one place&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ControllerAdvice
public class GlobalExceptionHandler {

    private String extractPath(WebRequest request) {
        return request.getDescription(false).replace("uri=", "");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleValidationErrors(
            MethodArgumentNotValidException ex, WebRequest request) {

        Map&amp;lt;String, String&amp;gt; errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        FieldError::getDefaultMessage,
                        (existing, replacement) -&amp;gt; existing
                ));

        ErrorResponse response = new ErrorResponse(
                HttpStatus.BAD_REQUEST,
                "Validation failed",
                errors
        );
        response.setPath(extractPath(request));
        return new ResponseEntity&amp;lt;&amp;gt;(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(DuplicateRollNumberException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleDuplicateRoll(
            DuplicateRollNumberException ex, WebRequest request) {
        ErrorResponse response = new ErrorResponse(HttpStatus.CONFLICT, ex.getMessage());
        response.setPath(extractPath(request));
        return new ResponseEntity&amp;lt;&amp;gt;(response, HttpStatus.CONFLICT);
    }

    @ExceptionHandler(StudentNotFoundException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleStudentNotFound(
            StudentNotFoundException ex, WebRequest request) {
        ErrorResponse response = new ErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage());
        response.setPath(extractPath(request));
        return new ResponseEntity&amp;lt;&amp;gt;(response, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(InvalidDepartmentCodeException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleInvalidDepartment(
            InvalidDepartmentCodeException ex, WebRequest request) {
        ErrorResponse response = new ErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage());
        response.setPath(extractPath(request));
        return new ResponseEntity&amp;lt;&amp;gt;(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleOtherErrors(
            Exception ex, WebRequest request) {
        ErrorResponse response = new ErrorResponse(
                HttpStatus.INTERNAL_SERVER_ERROR,
                "An unexpected error occurred"
        );
        response.setPath(extractPath(request));
        return new ResponseEntity&amp;lt;&amp;gt;(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Example Output (JSON)
&lt;/h2&gt;

&lt;p&gt;When a user sends bad data, your API will respond like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;:
{
  "timestamp": "2025-05-23T12:45:00",
  "status": 400,
  "error": "Bad Request",
  "message": "Validation failed",
  "path": "/api/students",
  "details": {
    "name": "Name must not be blank",
    "email": "Invalid email format"
  }
}

{
  "timestamp": "2025-05-23T12:45:00",
  "status": 404,
  "error": "Not Found",
  "message": "Student not found with roll number: 23CS001",
  "path": "/api/students/23CS001"
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Building a Student Management API with Spring Boot: A Step-by-Step Guide</title>
      <dc:creator>Mohammed Quasim D A</dc:creator>
      <pubDate>Mon, 19 May 2025 10:05:55 +0000</pubDate>
      <link>https://forem.com/mohammedquasimda/building-a-student-management-api-with-spring-boot-a-step-by-step-guide-47aa</link>
      <guid>https://forem.com/mohammedquasimda/building-a-student-management-api-with-spring-boot-a-step-by-step-guide-47aa</guid>
      <description>&lt;p&gt;github:&lt;a href="https://github.com/mohammedQuasimDA/smart-campus" rel="noopener noreferrer"&gt;https://github.com/mohammedQuasimDA/smart-campus&lt;/a&gt; &lt;br&gt;
If you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    Have doubts about any part of this guide
    Find something confusing or unclear
    Notice typos/errors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please reach out in the comments/DMs—I’d be delighted to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    Clarify concepts
    Fix mistakes promptly
    Improve this resource for everyone
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your feedback helps make this article more accurate and helpful for future readers! &lt;/p&gt;

&lt;p&gt;This project is a Student Management System built as a RESTful API using Spring Boot. It allows you to perform CRUD (Create, Read, Update, Delete) operations on student records, such as:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;    Adding new students&lt;/li&gt;
&lt;li&gt;    Retrieving student details&lt;/li&gt;
&lt;li&gt;    Updating student information&lt;/li&gt;
&lt;li&gt;    Deleting student dent records&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;🚀 Getting Started&lt;br&gt;
go to &lt;a href="https://start.spring.io/" rel="noopener noreferrer"&gt;https://start.spring.io/&lt;/a&gt; or search "spring initializr" in google&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
- project:maven
- language:java
- Spring boot:3.4.5 (or any version of your choice)
- Group: this is basically your company name in reverse order. like google.com--&amp;gt;com.google  if you are individual you can just com.your_name
- Artifact: give your project an artifact name, e.g., “demo.”
- Name: enter a name for your project, e.g., “SpringBootDemo.”
- Description: this field is optional.
- Package name: define your base package automatically generated you can also change it but it is combo of group and artifact , e.g., “com.learning.demo.”
- Packaging: choose “Jar” for a standalone JAR file.
- java:21
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Dependencies:
1.     Spring Web
2.     Spring data JPA
3.     Mysql driver

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now click on Generate which will generate a zip ,extract it and open in IDE&lt;/p&gt;

&lt;p&gt;My project name is smartcampus so it creates an folder with the same name&lt;br&gt;
inside it you will find "src" folder under it "main" under it "java"&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  1. Understanding the Model Layer
&lt;/h2&gt;

&lt;p&gt;The Model layer represents the structure of data in your application. Think of it like blueprints for the data you store in the database.&lt;/p&gt;

&lt;p&gt;Below is the folder struct we gonna create&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
               |-&amp;gt;Student.java
               |-&amp;gt;Department(enum)
           |-&amp;gt;converter
               |-&amp;gt;DepartmentConverter.java
      |-&amp;gt;resources

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.model;

import java.time.LocalDate;

import com.sc.smartcampus.converter.DepartmentConverter;
import com.sc.smartcampus.validation.ValidRollNumber;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;

@Entity
@Table(name = "students",indexes = @Index(columnList = "rollNumber",unique = true))
public class Student {

    @Id
    @Column(unique = true, length = 7) // Set to maximum possible length
    @ValidRollNumber
    private String rollNumber;

    @NotBlank(message = "Name is mandatory")
    @Size(min = 2, max = 50, message = "Name must be 2-50 characters")
    private String name;

    @Email(message = "Invalid email format")
    @Column(unique = true)
    private String email;

    @Column(name = "department")
    @Convert(converter = DepartmentConverter.class)
    private Department department;

    @NotNull(message = "Enrollment date is required")
    private LocalDate enrollmentDate;
    //getter setter , all args and no args construtor

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;• @Entity: Tells Spring Boot this class represents a database table.&lt;br&gt;
• name = "students": Sets the name of the table in the database to students.&lt;br&gt;
• indexes = @Index(...): Creates a database index on the rollNumber column to speed up search queries and enforce uniqueness.&lt;br&gt;
• unique = true: Ensures that no two students can have the same roll number.&lt;br&gt;
• &lt;a class="mentioned-user" href="https://dev.to/id"&gt;@id&lt;/a&gt;: Marks this field as the primary key (unique identifier).&lt;br&gt;
• &lt;a class="mentioned-user" href="https://dev.to/column"&gt;@column&lt;/a&gt;: Configures the database column.&lt;br&gt;
    • unique = true: Ensures no two rows can have the same value.&lt;br&gt;
    • length = 7: Limits the max characters to 7 (for example, 22BCS01).&lt;br&gt;
• @ValidRollNumber:custom validation annotation // will show &lt;br&gt;
• @NotBlankEnsures that the field is not null or empty&lt;br&gt;
• @Size:Ensures that the name is between 2 and 50 characters long&lt;br&gt;
• @Email:Makes sure the email field is a valid email address (like &lt;a href="mailto:test@example.com"&gt;test@example.com&lt;/a&gt;)&lt;br&gt;
• &lt;a class="mentioned-user" href="https://dev.to/column"&gt;@column&lt;/a&gt;(name = "department"): Creates a column named "department"&lt;br&gt;
• @Convert(...): Uses a custom converter (here, DepartmentConverter) to convert the Department enum to a code like "CS" and vice versa.//will show&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.model;

public enum Department {
    // Core Engineering
    AEROSPACE("AE", "Aerospace Engineering"),
    AUTOMOBILE("AU", "Automobile Engineering"),
    BIOTECH("BT", "Biotechnology"),
    CHEMICAL("CH", "Chemical Engineering"),
    CIVIL("CE", "Civil Engineering"),
    COMPUTER_SCIENCE("CS", "Computer Science"),
    COMPUTER_ENGINEERING("CSE", "Computer Science Engineering"),
    ELECTRICAL("EE", "Electrical Engineering"),
    ELECTRONICS("EC", "Electronics Engineering"),
    ELECTRONICS_COMMUNICATION("ECE", "Electronics and Communication"),
    ENVIRONMENTAL("EN", "Environmental Engineering"),
    INDUSTRIAL("IE", "Industrial Engineering"),
    INFORMATION_TECH("IT", "Information Technology"),
    INSTRUMENTATION("IC", "Instrumentation and Control"),
    MECHANICAL("ME", "Mechanical Engineering"),
    MECHATRONICS("MT", "Mechatronics"),
    METALLURGY("ML", "Metallurgical Engineering"),
    MINING("MN", "Mining Engineering"),
    PETROLEUM("PE", "Petroleum Engineering"),
    PRODUCTION("PD", "Production Engineering"),
    ROBOTICS("RB", "Robotics Engineering"),
    TEXTILE("TE", "Textile Engineering"),
    ARTIFICIAL_INTELLIGENCE("AI", "Artificial Intelligence"),
    DATA_SCIENCE("DS", "Data Science"),
    CYBER_SECURITY("CY", "Cyber Security"),
    CLOUD_COMPUTING("CC", "Cloud Computing"),
    IOT("IO", "Internet of Things");

    private final String code;
    private final String fullName;

    Department(String code, String fullName) {
        this.code = code;
        this.fullName = fullName;
    }

    public String getCode() {
        return code;
    }

    public String getFullName() {
        return fullName;
    }

    // Helper method to get department from code
    public static Department fromCode(String code) {
        for (Department dept : values()) {
            if (dept.code.equalsIgnoreCase(code)) {
                return dept;
            }
        }
        throw new IllegalArgumentException("Invalid department code: " + code);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This class is a Java enum (enumeration) called Department, and it's used to define a fixed list of engineering departments along with a short code and full name for each one&lt;/p&gt;

&lt;h3&gt;
  
  
  Purpose of Department enum
&lt;/h3&gt;

&lt;p&gt;This enum helps you:&lt;br&gt;
    1. Store departments using short codes like "CS" or "ME" in the database.&lt;br&gt;
    2. Show full names like "Computer Science" or "Mechanical Engineering" in the UI.&lt;/p&gt;

&lt;p&gt;• code: Short version like "CS" or "ME".&lt;br&gt;
• fullName: Full readable name like "Computer Science"&lt;/p&gt;

&lt;p&gt;fromCode() Method convert a code (like "ME") back into an MECHANICAL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.converter;

import com.sc.smartcampus.model.Department;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter(autoApply = true)
public class DepartmentConverter implements AttributeConverter&amp;lt;Department, String&amp;gt; {

    @Override
    public String convertToDatabaseColumn(Department department) {
        if (department == null) return null;
        return department.getCode(); // store "ME" instead of "MECHANICAL"
    }

    @Override
    public Department convertToEntityAttribute(String code) {
        if (code == null) return null;
        return Department.fromCode(code); // convert "ME" back to MECHANICAL
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Converter&lt;/p&gt;

&lt;h3&gt;
  
  
  Problem It Solves
&lt;/h3&gt;

&lt;p&gt;By default, if you use an enum in a JPA entity (like Department department in Student), it will store it in the database either as:&lt;br&gt;
    • The ordinal (position number, like 0, 1, 2) — not readable.&lt;br&gt;
    • Or the enum name (like "MECHANICAL").&lt;br&gt;
But you want to store the short code instead, like "ME" or "CS". Why?&lt;br&gt;
✅ It's compact&lt;br&gt;
✅ It's readable&lt;br&gt;
✅ It's customized to your preference ("CS" instead of "COMPUTER_SCIENCE")&lt;br&gt;
To do this, we use a custom converter with JPA: DepartmentConverter.&lt;/p&gt;

&lt;p&gt;@Converter(autoApply = true)&lt;br&gt;
Automatically use this converter for any Department type in your entity classes&lt;/p&gt;

&lt;p&gt;AttributeConverter&lt;br&gt;
will convert between the Department enum (Java side) and a String (DB side)&lt;/p&gt;
&lt;h3&gt;
  
  
  validation
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
                   |-&amp;gt;RollNumberValidator.java
                   |-&amp;gt;ValidRollNumber(@interface)
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In our model we have @ValidRollNumber for private String rollNumber; which was a custome&lt;br&gt;
What We're Doing Here&lt;br&gt;
We're creating a custom validation annotation that checks if a roll number:&lt;br&gt;
    1. Follows the correct pattern like 23CS001 (2-digit year + department code + 3 digits)&lt;br&gt;
    2. Has a valid department code like CS, ME, EC, etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Documented
@Constraint(validatedBy = RollNumberValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidRollNumber {
    String message() default "Invalid roll number or department code";
    Class&amp;lt;?&amp;gt;[] groups() default {};
    Class&amp;lt;? extends Payload&amp;gt;[] payload() default {};
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;• @Constraint: This tells Spring which validator class will handle this annotation (in our case, RollNumberValidator).&lt;br&gt;
• @Target(ElementType.FIELD): Can be used on fields.&lt;br&gt;
• @Retention(RUNTIME): The annotation should be available at runtime.&lt;/p&gt;

&lt;p&gt;String message() default "Invalid roll number or department code";&lt;br&gt;
    Class&amp;lt;?&amp;gt;[] groups() default {};&lt;br&gt;
    Class&amp;lt;? extends Payload&amp;gt;[] payload() default {};&lt;/p&gt;

&lt;p&gt;are required parts of every custom validation annotation in Spring Boot (using Jakarta Bean Validation).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.validation;

import com.sc.smartcampus.model.Department;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class RollNumberValidator implements ConstraintValidator&amp;lt;ValidRollNumber, String&amp;gt; {

    @Override
    public boolean isValid(String rollNumber, ConstraintValidatorContext context) {
        if (rollNumber == null || !rollNumber.matches("^\\d{2}[A-Z]{1,2}\\d{3}$")) {
            return false; // format is invalid
        }

        // extract department code
        String deptCode = rollNumber.substring(2, rollNumber.length() - 3);
        try {
            Department.fromCode(deptCode); // checks if dept code is valid
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;public class RollNumberValidator implements ConstraintValidator--&amp;gt;&lt;br&gt;
• This is a custom validator class for the annotation @ValidRollNumber.&lt;br&gt;
• It tells Spring how to validate a String field (like a roll number).&lt;br&gt;
• ConstraintValidator&lt;a&gt;: Here, A = ValidRollNumber (custom annotation), and T = String (type of the field being validated).&lt;br&gt;
rollNumber.substring(2, rollNumber.length() - 3);--&amp;gt;it takes only the code from the pattern 21ME093--&amp;gt;ME&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Repository Layer
&lt;/h2&gt;

&lt;p&gt;In Spring Boot, the repository layer is used to interact with the database. It contains the code to save, find, delete, or update data.&lt;br&gt;
Spring Data JPA makes this super simple — you don’t need to write SQL for common tasks!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
               |-&amp;gt;repository
                   |-&amp;gt; StudentRepository  
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.sc.smartcampus.model.Student;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface StudentRepository extends JpaRepository&amp;lt;Student, String&amp;gt; {

    @Query("SELECT MAX(s.rollNumber) FROM Student s WHERE s.rollNumber LIKE :pattern")
    String findMaxRollNumberByPattern(@Param("pattern") String pattern);

    @Query("SELECT s FROM Student s WHERE LOWER(s.name) LIKE LOWER(CONCAT('%', :keyword, '%')) " +
            "OR LOWER(s.email) LIKE LOWER(CONCAT('%', :keyword, '%')) " +
            "OR LOWER(s.rollNumber) LIKE LOWER(CONCAT('%', :keyword, '%'))")
    List&amp;lt;Student&amp;gt; searchByKeyword(@Param("keyword") String keyword);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;--&amp;gt;The &lt;/p&gt;

&lt;p&gt;here JPA give you many querys like findById() etc.&lt;/p&gt;

&lt;p&gt;but sometime we need custom queries like to get maximum roll number&lt;br&gt;
&lt;code&gt;@Query("SELECT MAX(s.rollNumber) FROM Student s WHERE s.rollNumber LIKE :pattern")&lt;br&gt;
String findMaxRollNumberByPattern(@Param("pattern") String pattern);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;String pattern --&amp;gt;it wil have a pattern[17ME204] which user passes&lt;br&gt;
so what we do is that we search the DB with the same pattern and find the highest roll number.&lt;br&gt;
When adding a new student, you might want to auto-generate the next roll number based on a pattern&lt;/p&gt;

&lt;p&gt;&lt;code&gt;@Query("SELECT s FROM Student s WHERE LOWER(s.name) LIKE LOWER(CONCAT('%', :keyword, '%')) " +&lt;br&gt;
       "OR LOWER(s.email) LIKE LOWER(CONCAT('%', :keyword, '%')) " +&lt;br&gt;
       "OR LOWER(s.rollNumber) LIKE LOWER(CONCAT('%', :keyword, '%'))")&lt;br&gt;
List&amp;lt;Student&amp;gt; searchByKeyword(@Param("keyword") String keyword);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Allows you to search students by name, email, or roll number — case-insensitive and partial match&lt;/p&gt;
&lt;h2&gt;
  
  
  3. DTOs (Data Transfer Objects)
&lt;/h2&gt;

&lt;p&gt;A DTO (Data Transfer Object) is a simple Java class used to transfer data between the frontend and backend.&lt;br&gt;
We use DTOs to:&lt;br&gt;
    • Control what data is exposed to clients.&lt;br&gt;
    • Separate internal entity logic from external data exchange.&lt;br&gt;
    • Apply input validation rules cleanly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
               |-&amp;gt;repository
               |-&amp;gt;dto
                   |-&amp;gt; StudentRequestDTO
                   |-&amp;gt; StudentResponseDTO  
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  StudentRequestDTO – When client sends data to backend (POST/PUT)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.dto;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

import java.time.LocalDate;

public class StudentRequestDTO {

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters")
    private String name;

    @Email(message = "Invalid email format")
    @NotBlank(message = "Email is required")
    private String email;

    @NotBlank(message = "Department code is required")
    private String department;

    @NotNull(message = "Enrollment date is required")
    private LocalDate enrollmentDate;

    public StudentRequestDTO() {
    }

    public StudentRequestDTO(String name, String email, String department, LocalDate enrollmentDate) {
        this.name = name;
        this.email = email;
        this.department = department;
        this.enrollmentDate = enrollmentDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public LocalDate getEnrollmentDate() {
        return enrollmentDate;
    }

    public void setEnrollmentDate(LocalDate enrollmentDate) {
        this.enrollmentDate = enrollmentDate;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;• &lt;a class="mentioned-user" href="https://dev.to/notblank"&gt;@notblank&lt;/a&gt;: Field cannot be empty or only spaces.&lt;br&gt;
• @Size(min, max): Limits name length.&lt;/p&gt;
&lt;h3&gt;
  
  
  StudentResponseDTO
&lt;/h3&gt;

&lt;p&gt;When backend sends data to client (GET)&lt;br&gt;
 Purpose:&lt;br&gt;
This DTO is used when the backend sends student data to the frontend. It contains:&lt;br&gt;
    • The generated roll number&lt;br&gt;
    • Both department code (CS) and full name (Computer Science)&lt;br&gt;
    • All other student info&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.dto;

import java.time.LocalDate;

public class StudentResponseDTO {

    private String rollNumber;
    private String name;
    private String email;
    private String department;          // e.g., "CS"
    private String departmentFullName;  // e.g., "Computer Science"
    private LocalDate enrollmentDate;

    public StudentResponseDTO() {
    }

    public StudentResponseDTO(String rollNumber, String name, String email,
                              String department, String departmentFullName,
                              LocalDate enrollmentDate) {
        this.rollNumber = rollNumber;
        this.name = name;
        this.email = email;
        this.department = department;
        this.departmentFullName = departmentFullName;
        this.enrollmentDate = enrollmentDate;
    }

    public String getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getDepartmentFullName() {
        return departmentFullName;
    }

    public void setDepartmentFullName(String departmentFullName) {
        this.departmentFullName = departmentFullName;
    }

    public LocalDate getEnrollmentDate() {
        return enrollmentDate;
    }

    public void setEnrollmentDate(LocalDate enrollmentDate) {
        this.enrollmentDate = enrollmentDate;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5c2emqzuy2a6o9p6p8kt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5c2emqzuy2a6o9p6p8kt.png" alt="Image description" width="778" height="120"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Service
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What is a Service Interface?
&lt;/h3&gt;

&lt;p&gt;In Spring Boot, the service layer is where:&lt;br&gt;
    • Core business logic is written&lt;br&gt;
    • The controller sends requests here&lt;br&gt;
    • The repository is called from here to talk to the database&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
               |-&amp;gt;repository
               |-&amp;gt;dto
               |-&amp;gt;service
                   |-&amp;gt;impl
                        |-&amp;gt;StudentServiceImpl.java
                   |-&amp;gt;StudentService(interface) 
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.service;

import com.sc.smartcampus.dto.StudentRequestDTO;
import com.sc.smartcampus.dto.StudentResponseDTO;

import java.util.List;

public interface StudentService {

    StudentResponseDTO createStudent(StudentRequestDTO dto);

    StudentResponseDTO getStudentByRollNumber(String rollNumber);

    StudentResponseDTO updateStudent(String rollNumber, StudentRequestDTO dto);

    void deleteStudent(String rollNumber);

    List&amp;lt;StudentResponseDTO&amp;gt; getAllStudents();

    List&amp;lt;StudentResponseDTO&amp;gt; searchStudents(String keyword);

    String generateNextRollNumber(String year, String departmentCode);
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  What Is StudentServiceImpl?
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;• It implements the methods defined in your StudentService interface.
• Handles all business logic: creating, updating, deleting, searching, and managing roll numbers.
• Talks to the repository (StudentRepository) to interact with the database.
• Converts data between the DTOs and Entity classes.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private StudentRepository studentRepository;

public StudentServiceImpl(StudentRepository studentRepository) {
    this.studentRepository = studentRepository;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use/access the repository&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
package com.sc.smartcampus.service.impl;

import com.sc.smartcampus.dto.StudentRequestDTO;
import com.sc.smartcampus.dto.StudentResponseDTO;
import com.sc.smartcampus.model.Department;
import com.sc.smartcampus.model.Student;
import com.sc.smartcampus.repository.StudentRepository;
import com.sc.smartcampus.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {


    private StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    private StudentResponseDTO mapToResponseDTO(Student student) {
        StudentResponseDTO dto = new StudentResponseDTO();
        dto.setRollNumber(student.getRollNumber());
        dto.setName(student.getName());
        dto.setEmail(student.getEmail());
        dto.setDepartment(student.getDepartment().getCode());
        dto.setDepartmentFullName(student.getDepartment().getFullName());
        dto.setEnrollmentDate(student.getEnrollmentDate());
        return dto;
    }


// Implement all methods here...

    @Override
    public StudentResponseDTO createStudent(StudentRequestDTO dto) {
        // 1. Convert department code string to enum (throws exception if invalid)
        Department department = Department.fromCode(dto.getDepartment());

        // 2. Generate the year part from enrollment date
        String year = String.valueOf(dto.getEnrollmentDate().getYear()).substring(2); // last two digits, e.g. "23"

        // 3. Generate the next roll number for this year + department
        String nextRollNumber = generateNextRollNumber(year, department.getCode());

        // 4. Create new Student entity
        Student student = new Student();
        student.setRollNumber(nextRollNumber);
        student.setName(dto.getName());
        student.setEmail(dto.getEmail());
        student.setDepartment(department);
        student.setEnrollmentDate(dto.getEnrollmentDate());

        // 5. Save student entity
        student = studentRepository.save(student);

        // 6. Convert to response DTO and return
        return mapToResponseDTO(student);
    }



    @Override
    public StudentResponseDTO getStudentByRollNumber(String rollNumber) {
        Student student = studentRepository.findById(rollNumber)
                .orElseThrow(() -&amp;gt; new RuntimeException("Student not found with roll number: " + rollNumber));
        return mapToResponseDTO(student);
    }


    @Override
    public StudentResponseDTO updateStudent(String rollNumber, StudentRequestDTO dto) {
        // 1. Fetch the existing student by rollNumber
        Student student = studentRepository.findById(rollNumber)
                .orElseThrow(() -&amp;gt; new RuntimeException("Student not found with roll number: " + rollNumber));

        // 2. Update the fields from the DTO (except rollNumber, which is immutable)
        student.setName(dto.getName());
        student.setEmail(dto.getEmail());

        // 3. Convert and update department (validate department code)
        Department department = Department.fromCode(dto.getDepartment());
        student.setDepartment(department);

        // 4. Update enrollment date
        student.setEnrollmentDate(dto.getEnrollmentDate());

        // 5. Save the updated student
        student = studentRepository.save(student);

        // 6. Convert to response DTO and return
        return mapToResponseDTO(student);
    }


    @Override
    public void deleteStudent(String rollNumber) {
        // Check if student exists, else throw exception
        Student student = studentRepository.findById(rollNumber)
                .orElseThrow(() -&amp;gt; new RuntimeException("Student not found with roll number: " + rollNumber));

        // Delete the student
        studentRepository.delete(student);
    }


    @Override
    public List&amp;lt;StudentResponseDTO&amp;gt; getAllStudents() {
        List&amp;lt;Student&amp;gt; students = studentRepository.findAll();
        return students.stream()
                .map(this::mapToResponseDTO)
                .collect(Collectors.toList());
    }


    @Override
    public List&amp;lt;StudentResponseDTO&amp;gt; searchStudents(String keyword) {
        List&amp;lt;Student&amp;gt; students = studentRepository.searchByKeyword(keyword);
        return students.stream()
                .map(this::mapToResponseDTO)
                .collect(Collectors.toList());
    }


    @Override
    public String generateNextRollNumber(String year, String departmentCode) {
        // 1. Create the pattern to find max existing roll numbers for the year+dept
        // Example pattern: "21CS%" to match roll numbers starting with 21CS
        String pattern = year + departmentCode + "%";

        // 2. Get the max existing roll number with this pattern from DB
        String maxRollNumber = studentRepository.findMaxRollNumberByPattern(pattern);

        int nextSerial = 1; // default if no existing roll numbers

        if (maxRollNumber != null) {
            // Extract the last 3 digits of the roll number (serial number)
            String serialStr = maxRollNumber.substring(maxRollNumber.length() - 3);
            try {
                int serialNum = Integer.parseInt(serialStr);
                nextSerial = serialNum + 1;
            } catch (NumberFormatException e) {
                // fallback if parsing fails, start from 1
                nextSerial = 1;
            }
        }

        // 3. Format the serial to be 3 digits with leading zeros (e.g., 001, 042)
        String serialFormatted = String.format("%03d", nextSerial);

        // 4. Build and return the next roll number string
        return year + departmentCode + serialFormatted;
    }


    // You can add private helper methods if needed, for example, a mapper from Student to DTO
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  createStudent(StudentRequestDTO dto)
&lt;/h4&gt;

&lt;p&gt;Converts StudentRequestDTO → Student → StudentResponseDTO&lt;br&gt;
Steps:&lt;br&gt;
    1. Converts department string to a valid Department enum using Department.fromCode().&lt;br&gt;
    2.  Extracts year from enrollment date (e.g., 2023 → "23").&lt;br&gt;
    3.  Generates the next available roll number like 23CS001.&lt;br&gt;
    4.  Creates and saves a Student entity.&lt;br&gt;
    5.  Converts entity to response DTO.&lt;/p&gt;
&lt;h4&gt;
  
  
  getStudentByRollNumber(String rollNumber)
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;•  Finds a student using studentRepository.findById(...).
•  Throws a RuntimeException if not found.
•  Returns a StudentResponseDTO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  updateStudent(String rollNumber, StudentRequestDTO dto)
&lt;/h4&gt;

&lt;p&gt;Steps:&lt;br&gt;
    1.  Fetch existing student.&lt;br&gt;
    2.  Update fields except roll number.&lt;br&gt;
    3.  Validate department again using fromCode.&lt;br&gt;
    4. Save and return updated StudentResponseDTO&lt;/p&gt;
&lt;h4&gt;
  
  
  deleteStudent(String rollNumber)
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;•  Checks if student exists.
•  Deletes using studentRepository.delete()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  getAllStudents()
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;•  Fetches all students.
• Maps each entity to a StudentResponseDTO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  searchStudents(String keyword)
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;• Uses a custom query to search by name, email, or roll number.
•  Converts results to DTOs.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  generateNextRollNumber(String year, String departmentCode)
&lt;/h4&gt;

&lt;p&gt;Logic:&lt;br&gt;
    1. Constructs a search pattern like 23CS%.&lt;br&gt;
    2. Finds the current highest roll number matching the pattern.&lt;br&gt;
    3. Extracts the last 3 digits → increments → formats to 3 digits (e.g., 003).&lt;br&gt;
    4. Returns the new roll number: e.g., 23CS004&lt;/p&gt;
&lt;h4&gt;
  
  
  mapToResponseDTO
&lt;/h4&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;• Converts a Student entity into a readable API-friendly response object (StudentResponseDTO).
• Useful to prevent exposing internal entity structure.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Controller
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
               |-&amp;gt;repository
               |-&amp;gt;dto
               |-&amp;gt;service
               |-controller
                   |-&amp;gt;StudentController 
      |-&amp;gt;resources
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Purpose of StudentController
&lt;/h3&gt;

&lt;p&gt;This class handles all HTTP requests related to the Student resource. It's part of the Controller layer in a Spring Boot application, which connects the client (frontend/API consumer) to the Service layer.&lt;br&gt;
You’re using:&lt;br&gt;
    • @RestController – to mark this class as a REST controller.&lt;br&gt;
@RequestMapping("/api/students") – so all routes start with /api/students&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.sc.smartcampus.controller;

import com.sc.smartcampus.dto.StudentRequestDTO;
import com.sc.smartcampus.dto.StudentResponseDTO;
import com.sc.smartcampus.service.StudentService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 1. Create Student
    @PostMapping
    public ResponseEntity&amp;lt;StudentResponseDTO&amp;gt; createStudent(@Valid @RequestBody StudentRequestDTO dto) {
        StudentResponseDTO created = studentService.createStudent(dto);
        return ResponseEntity.ok(created);
    }

    // 2. Get Student by Roll Number
    @GetMapping("/{rollNumber}")
    public ResponseEntity&amp;lt;StudentResponseDTO&amp;gt; getStudentByRollNumber(@PathVariable String rollNumber) {
        StudentResponseDTO student = studentService.getStudentByRollNumber(rollNumber);
        return ResponseEntity.ok(student);
    }

    // 3. Update Student by Roll Number
    @PutMapping("/{rollNumber}")
    public ResponseEntity&amp;lt;StudentResponseDTO&amp;gt; updateStudent(@PathVariable String rollNumber,
                                                            @Valid @RequestBody StudentRequestDTO dto) {
        StudentResponseDTO updated = studentService.updateStudent(rollNumber, dto);
        return ResponseEntity.ok(updated);
    }

    // 4. Delete Student by Roll Number
    @DeleteMapping("/{rollNumber}")
    public ResponseEntity&amp;lt;Void&amp;gt; deleteStudent(@PathVariable String rollNumber) {
        studentService.deleteStudent(rollNumber);
        return ResponseEntity.noContent().build();
    }

    // 5. Get All Students
    @GetMapping
    public ResponseEntity&amp;lt;List&amp;lt;StudentResponseDTO&amp;gt;&amp;gt; getAllStudents() {
        List&amp;lt;StudentResponseDTO&amp;gt; students = studentService.getAllStudents();
        return ResponseEntity.ok(students);
    }

    // 6. Search Students by keyword
    @GetMapping("/search")
    public ResponseEntity&amp;lt;List&amp;lt;StudentResponseDTO&amp;gt;&amp;gt; searchStudents(@RequestParam String keyword) {
        List&amp;lt;StudentResponseDTO&amp;gt; results = studentService.searchStudents(keyword);
        return ResponseEntity.ok(results);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;• @PostMapping – handles POST /api/students.&lt;br&gt;
• @RequestBody – reads JSON body into a Java object.&lt;br&gt;
• &lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt; – triggers validation (e.g., &lt;a class="mentioned-user" href="https://dev.to/notblank"&gt;@notblank&lt;/a&gt;, @ValidRollNumber).&lt;br&gt;
• Returns ResponseEntity.ok(...) with the saved student data&lt;br&gt;
• @GetMapping("/{rollNumber}") – dynamic path parameter.&lt;br&gt;
• @PathVariable – binds the rollNumber from the URL&lt;br&gt;
• @PutMapping("/{rollNumber}")-used to update a full resource&lt;br&gt;
• @DeleteMapping("/{rollNumber}")-delte a resource&lt;br&gt;
• @RequestParam is used for query parameters like /api/students/search?keyword=john&lt;/p&gt;
&lt;h2&gt;
  
  
  Connect to Database
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--&amp;gt;smartcampus
  |-&amp;gt;src
    |-&amp;gt;main
      |-&amp;gt;java
         |-&amp;gt;com.sc.smartcampus
           |-&amp;gt;model
           |-&amp;gt;converter
           |-&amp;gt;validation
               |-&amp;gt;repository
               |-&amp;gt;dto
               |-&amp;gt;service
               |-controller 
      |-&amp;gt;resources
               |-&amp;gt;application.properties
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.datasource.url=jdbc:mysql://localhost:3306/database_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

server.port=9090--&amp;gt; i used port 9090 by default it is 8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;We have create the spring boot app now run and pass api via postman&lt;br&gt;
if you are using default port change 9090 to 8080&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;POST http://localhost:9090/api/students
Content-Type: application/json

{
  "name": "Joqsadhn a Doe",
  "email": "joewqqhn.wdose@example.com",
  "department": "CS",
  "enrollmentDate": "2023-08-15"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET http://localhost:9090/api/students
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET http://localhost:9090/api/students/23CS001
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
DELETE http://localhost:9090/api/students/21CS001
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET http://localhost:9090/api/students/search?keyword=john
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PUT http://localhost:9090/api/students/23CS001
Content-Type: application/json

{
"name": "John Doe Updated",
"email": "john.updated@example.com",
"department": "ME",
"enrollmentDate": "2023-08-20"
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>springboot</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
