REST로 CRUD 작업 구현하기
REST 엔드포인트를 통해 엔터티의 생성, 조회, 수정, 삭제 작업을 구현합니다.
REST로 CRUD 작업 구현하기은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 6개 중 5번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
CRUD Operations: The Basics
Welcome to implementing CRUD operations with Spring Boot! CRUD stands for Create, Read, Update, and Delete.
These are the four fundamental operations for persistent storage, allowing you to manage data in your application.
In REST APIs, each CRUD operation typically maps to a specific HTTP method.
Mapping CRUD to HTTP Methods
Understanding how CRUD maps to HTTP methods is key for RESTful design:
- Create (C): Handled by
POSTrequests. - Read (R): Handled by
GETrequests. - Update (U): Handled by
PUTrequests. - Delete (D): Handled by
DELETErequests.
We'll use a simple Product entity and its ProductRepository from previous lessons.
Implementing Create (POST)
To create a new resource, we use the POST HTTP method. In Spring Boot, this is handled by the @PostMapping annotation.
The new product data is sent in the request body, which Spring automatically maps to our Product object using @RequestBody.
Create Product Example
Here's how you'd create an endpoint to add a new product. Run it, then try adding a product via a tool like Postman (e.g., POST to /api/products with JSON body {"name": "Laptop", "price": 1200.0}).
package com.coddykit.crud;
import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}
@RestController
@RequestMapping("/api/products")
class ProductController {
@Autowired
private ProductRepository productRepository;
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productRepository.save(product);
}
}
@SpringBootApplication
class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}Implementing Read (GET)
Reading resources is done with the GET HTTP method. We'll create two types of read operations:
- Get all products: Maps to
@GetMapping. - Get a single product by ID: Maps to
@GetMapping("/{id}")using a@PathVariable.
When fetching by ID, we use Optional to handle cases where the product might not exist.
Read Products Example
This code adds methods to fetch all products and a single product by its ID. Notice the use of ResponseEntity to return a 404 if a product isn't found.
package com.coddykit.crud;
import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Optional;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}
@RestController
@RequestMapping("/api/products")
class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
Optional<Product> product = productRepository.findById(id);
return product.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
}
@SpringBootApplication
class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}Implementing Update (PUT)
To update an existing resource, we use the PUT HTTP method, annotated with @PutMapping.
The endpoint typically includes the resource's ID in the path (/{id}) to identify which item to update, and the updated data is sent in the @RequestBody.
Update Product Example
This method updates an existing product. It first checks if the product exists using the ID from the path. If found, it updates the fields from the request body and saves it.
package com.coddykit.crud;
import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.Optional;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}
@RestController
@RequestMapping("/api/products")
class ProductController {
@Autowired
private ProductRepository productRepository;
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(
@PathVariable Long id, @RequestBody Product productDetails) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product existingProduct = product.get();
existingProduct.setName(productDetails.getName());
existingProduct.setPrice(productDetails.getPrice());
return ResponseEntity.ok(productRepository.save(existingProduct));
} else {
return ResponseEntity.notFound().build();
}
}
}
@SpringBootApplication
class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}Implementing Delete (DELETE)
To remove a resource, we use the DELETE HTTP method, annotated with @DeleteMapping.
Similar to update, the ID of the resource to delete is passed as a @PathVariable. After deletion, it's common to return a 204 No Content status.
Delete Product Example
This method deletes a product by ID. It finds the product and, if present, deletes it. Returning ResponseEntity.noContent().build() is a good practice for successful deletions.
package com.coddykit.crud;
import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.Optional;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}
@RestController
@RequestMapping("/api/products")
class ProductController {
@Autowired
private ProductRepository productRepository;
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
productRepository.delete(product.get());
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
@SpringBootApplication
class CrudApplication {
public static void main(String[] args) {
SpringApplication.run(CrudApplication.class, args);
}
}Quick Check: HTTP Methods
Which HTTP method is typically used to update an existing resource in a REST API, and which one is for creating a new resource?
Recap: CRUD with REST
You've successfully learned how to implement all four CRUD operations using Spring Boot REST controllers!
- Create: Use
@PostMapping. - Read: Use
@GetMapping(for all or by ID). - Update: Use
@PutMapping. - Delete: Use
@DeleteMapping.
These are the building blocks for almost any data-driven API. Next, we'll explore validation and error handling!
자주 묻는 질문
“REST로 CRUD 작업 구현하기” 강의는 무료인가요?
네 — “REST로 CRUD 작업 구현하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
“REST로 CRUD 작업 구현하기”에서 뭘 배우나요?
REST 엔드포인트를 통해 엔터티의 생성, 조회, 수정, 삭제 작업을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 5번째 강의입니다.
“REST로 CRUD 작업 구현하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.