MODULE 5 · TOPIC 3 · VISUAL SPRING BOOT LAB

Spring Boot REST API with Spring Data JPA

A REST API exposes resource-oriented HTTP endpoints. Spring MVC maps requests to controller methods, converts JSON, and writes responses. Spring Data JPA generates repository implementations for entity persistence; Hibernate translates operations into SQL over JDBC. A service layer is useful for business rules and transaction boundaries. The browser labs model requests, HTTP status, SQL and committed records independently.

Browser-based Spring Boot simulations. Change inputs and trace HTTP requests, bean wiring, SQL, security decisions and tests. No real Java, HTTP server or database operations are executed.

1. REST request architecture — client to database

HTTP requests enter the embedded servlet server and DispatcherServlet. A controller calls a service or repository, the repository delegates to JPA, and Hibernate executes SQL. The result travels back as a DTO or response.

Why this example? Trace GET /students/{id} including found and missing rows.

Why this step happens
See all steps in this scenario
    Java / Spring Boot configuration
    HTTP / application / test outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected

    Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

    What this animation explains

    HTTP requests enter the embedded servlet server and DispatcherServlet. A controller calls a service or repository, the repository delegates to JPA, and Hibernate executes SQL. The result travels back as a DTO or response.

    Try and observe

    Change ID and inspect the result branch and HTTP response.

    2. Create resource — POST and JSON binding

    POST commonly creates a new resource. MVC deserializes a JSON request into an input object. Validation occurs before persistence; a successful create typically returns HTTP 201 and Location. This example manually validates the name.

    Why this example? Compare a valid student with a blank name. Observe whether a new row appears.

    Why this step happens
    See all steps in this scenario
      Java / Spring Boot configuration
      HTTP / application / test outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected

      Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

      What this animation explains

      POST commonly creates a new resource. MVC deserializes a JSON request into an input object. Validation occurs before persistence; a successful create typically returns HTTP 201 and Location. This example manually validates the name.

      Try and observe

      Try a blank name; the INSERT must not occur.

      3. Update resource — PUT and dirty checking

      PUT conventionally replaces the state of a known resource. Inside a transactional service, findById retrieves a managed entity. Changing its mapped fields causes dirty checking at flush; an absent ID should have explicit behavior. This lab chooses 404 rather than upsert.

      Why this example? Compare replacing an existing name and updating an absent resource.

      Why this step happens
      See all steps in this scenario
        Java / Spring Boot configuration
        HTTP / application / test outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected

        Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

        What this animation explains

        PUT conventionally replaces the state of a known resource. Inside a transactional service, findById retrieves a managed entity. Changing its mapped fields causes dirty checking at flush; an absent ID should have explicit behavior. This lab chooses 404 rather than upsert.

        Try and observe

        Observe old and new values and the UPDATE SQL.

        4. DELETE and database constraints

        Deleting a parent record may be blocked by a foreign key when dependent records remain. A successful deletion can return 204 No Content. An application should define how to handle absent IDs and constraint failures instead of returning misleading success.

        Why this example? Compare a successful delete with a database foreign-key rejection.

        Why this step happens
        See all steps in this scenario
          Java / Spring Boot configuration
          HTTP / application / test outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected

          Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

          What this animation explains

          Deleting a parent record may be blocked by a foreign key when dependent records remain. A successful deletion can return 204 No Content. An application should define how to handle absent IDs and constraint failures instead of returning misleading success.

          Try and observe

          Inspect whether the original row remains after rollback.

          5. Derived queries and parameterized SQL

          Spring Data derives queries from method names such as findByName. It interprets entity property names, then binds parameter values rather than interpolating client strings into SQL. Query methods must match actual entity properties.

          Why this example? Compare name lookup results for two values.

          Why this step happens
          See all steps in this scenario
            Java / Spring Boot configuration
            HTTP / application / test outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected

            Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

            What this animation explains

            Spring Data derives queries from method names such as findByName. It interprets entity property names, then binds parameter values rather than interpolating client strings into SQL. Query methods must match actual entity properties.

            Try and observe

            Switch name and inspect the bound parameter and result table.

            6. Pagination, sorting and JSON response

            Pageable specifies a zero-based page index, page size and sorting. A Page contains content and total information; a Slice can avoid a total count. A stable sort with a unique tie-breaker makes page boundaries predictable.

            Why this example? Compare first, second and empty pages with a fixed ID order.

            Why this step happens
            See all steps in this scenario
              Java / Spring Boot configuration
              HTTP / application / test outputConsole
              Data operationsCompact blocks
              CurrentResultError / rejected

              Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

              What this animation explains

              Pageable specifies a zero-based page index, page size and sorting. A Page contains content and total information; a Slice can avoid a total count. A stable sort with a unique tie-breaker makes page boundaries predictable.

              Try and observe

              Select different page sizes and inspect offset and returned IDs.

              API and configuration reference

              Refer to these APIs and settings while building a real Spring project.

              API / settingWhy and when to use it
              @RestControllerSerialize return values to response bodies
              @GetMapping / @PostMappingMap HTTP methods to resources
              @RequestBodyDeserialize the incoming body
              JpaRepository<Student, Long>Provide standard entity operations
              ResponseEntity.created(uri)Return 201 with a Location header
              PageRequest.of(0, 2)Request a zero-based page of size two

              Worked practical examples

              Follow these procedures with the Java 21 / Spring Boot 3.4.0 teaching project. Unless complete files are provided, the code is a focused snippet requiring the indicated imports, companion classes and configuration.

              1. Build the entity and repository

              Procedure

              1. Use the introduction POM and add spring-boot-starter-data-jpa and com.h2database:h2 (runtime).
              2. Save each of the two source fragments in its own named Java file in package demo.
              3. Set spring.datasource.url=jdbc:h2:mem:school and spring.jpa.hibernate.ddl-auto=create-drop for this disposable lab.
              4. Run the app with the controller in the next example.
              Code / configuration
              package demo;
              import jakarta.persistence.*;
              @Entity
              class Student {
                @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
                Long id;
                String name;
                protected Student() {}
                Student(String name) { this.name = name; }
                public Long getId() { return id; }
                public String getName() { return name; }
              }
              
              // StudentRepository.java
              package demo;
              import org.springframework.data.jpa.repository.JpaRepository;
              interface StudentRepository extends JpaRepository<Student, Long> {}
              Expected result: Hibernate creates the disposable Student table and Spring Data supplies a repository implementation.

              2. Expose and test a real HTTP endpoint

              Procedure

              1. Save the following controller in demo/StudentController.java.
              2. Run mvn spring-boot:run.
              3. POST JSON {"name":"Anu"} to http://localhost:8080/students with Content-Type application/json.
              4. Use the returned Location or ID in a GET request; try an unknown ID.
              Code / configuration
              package demo;
              import java.net.URI;
              import org.springframework.http.ResponseEntity;
              import org.springframework.web.bind.annotation.*;
              @RestController @RequestMapping("/students")
              class StudentController {
                private final StudentRepository repo;
                StudentController(StudentRepository repo) { this.repo=repo; }
                @GetMapping("/{id}") ResponseEntity<Student> get(@PathVariable Long id) {
                  return repo.findById(id).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
                }
                record Input(String name) {}
                @PostMapping ResponseEntity<Student> create(@RequestBody Input input) {
                  if (input.name()==null || input.name().isBlank()) return ResponseEntity.badRequest().build();
                  Student saved=repo.save(new Student(input.name()));
                  return ResponseEntity.created(URI.create("/students/"+saved.getId())).body(saved);
                }
              }
              Expected result: POST returns 201 and the saved student; GET returns 200 for its ID or 404 for an unknown one.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Predict the outcome for 999 absent in REST request architecture — client to database. Which path is taken and why?

              The controller maps absence to HTTP 404. Expected state: 404 Not Found.

              2. Predict the outcome for 999 → Priya in Update resource — PUT and dirty checking. Which path is taken and why?

              Assume NotFound is mapped to 404 by advice. Expected state: 404.

              3. Predict the outcome for Unknown in Derived queries and parameterized SQL. Which path is taken and why?

              Return matching entities to the service. Expected state: 0 matching rows.

              Hands-on practice and assessment

              Programming challenge

              Create Student entity, repository and controller in a Web + Data JPA project with H2. Send GET and POST requests, inspect returned JSON and test missing IDs. Add PUT and DELETE methods with explicit service-level transactions.

              Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.

              Quick assessment

              Key points and real Spring notes

              Use DTOs for larger applications, validate client data, parameterize queries and protect endpoints. H2 is an educational database; SQL and generated IDs depend on database and configuration.