💾Thananjhayan
← Back to notes

Spring Boot — Repository & CRUD Controller

July 20, 2025

Part (iv). One interface gives you CRUD for free; the controller exposes it explicitly.

Step 1 — The Repository

Create ItemRepository.java in com.example.IndexNo.repository. You write no code inside it — extending JpaRepository provides save, find, delete, etc.

package com.example.IndexNo.repository;

import com.example.IndexNo.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "items", path = "items")
public interface ItemRepository extends JpaRepository<Item, Integer> {
}

Because of @RepositoryRestResource (from the Rest Repositories dependency), Spring instantly gives you working REST links at /items with no controller at all. This alone can satisfy "Rest Repository interface".

Step 2 — The CRUD Controller

To show full CRUD explicitly, create ItemController.java in com.example.IndexNo.controller:

package com.example.IndexNo.controller;

import com.example.IndexNo.model.Item;
import com.example.IndexNo.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/items")
public class ItemController {

    @Autowired
    private ItemRepository repository;

    // CREATE
    @PostMapping
    public Item addItem(@RequestBody Item item) {
        return repository.save(item);
    }

    // READ all
    @GetMapping
    public List<Item> getAllItems() {
        return repository.findAll();
    }

    // READ one by id
    @GetMapping("/{id}")
    public Item getItem(@PathVariable int id) {
        return repository.findById(id).orElse(null);
    }

    // UPDATE
    @PutMapping("/{id}")
    public Item updateItem(@PathVariable int id, @RequestBody Item item) {
        item.setItemCode(id);
        return repository.save(item);
    }

    // DELETE
    @DeleteMapping("/{id}")
    public String deleteItem(@PathVariable int id) {
        repository.deleteById(id);
        return "Item deleted with id: " + id;
    }
}

What each annotation does

  • @RestController — handles web requests and returns data (JSON).
  • @RequestMapping("/api/items") — every link in the class starts with /api/items.
  • @PostMapping = create, @GetMapping = read, @PutMapping = update, @DeleteMapping = delete.
  • @Autowired — Spring hands you the repository object; you don't create it.

Next: [[spring-boot-run-and-test]]. Prereq: [[spring-boot-entity]].

💬 Comments