0Pricing
Spring Boot 4 Microservices & REST APIs · 강의

CRUD 작업 수행

Spring Data JPA의 강력한 리포지토리 메서드를 사용하여 생성, 조회, 수정, 삭제 작업을 구현합니다.

CRUD 작업 수행은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 6개 중 6번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

CRUD Operations: The Core

Welcome to the heart of data management! Today, we'll master CRUD operations with Spring Data JPA. CRUD is a fundamental concept for almost any application that interacts with a database.

  • Create: Adding new data.
  • Read: Retrieving existing data.
  • Update: Modifying existing data.
  • Delete: Removing data.

Spring Data JPA provides powerful, easy-to-use methods for all of these!

Our Example Setup: Product

To demonstrate CRUD, we'll use a simple Product entity and its corresponding repository. You would have learned to set these up in previous lessons.

Here's our basic Product entity and ProductRepository interface:

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@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;
    }

    // Getters and Setters (omitted for brevity)
    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; }

    @Override
    public String toString() {
        return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
    }
}

// ProductRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

Creating New Data (C)

To create new data, we use the save() method from our repository. If the entity's ID is null (or 0 for primitive types), Spring Data JPA knows it's a new entry and will insert it into the database.

Try creating a new product:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        Product newProduct = new Product("Laptop", 1200.00);
        Product savedProduct = productRepository.save(newProduct);
        System.out.println("Created: " + savedProduct);
    }
}

Reading Data by ID (R)

To read a specific item, you often need its unique identifier (ID). The findById(ID id) method is perfect for this. It returns an Optional, which helps handle cases where the item might not exist.

Let's find the product we just created:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        Product newProduct = new Product("Keyboard", 75.00);
        Product savedProduct = productRepository.save(newProduct);
        System.out.println("Created: " + savedProduct);

        Optional<Product> foundProduct = productRepository.findById(savedProduct.getId());
        foundProduct.ifPresent(p -> System.out.println("Found: " + p));
    }
}

Reading All Data (R)

What if you want to see all the products in your database? The findAll() method does exactly that! It returns a List of all entities of that type.

Let's retrieve all products:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        productRepository.save(new Product("Mouse", 25.00));
        productRepository.save(new Product("Monitor", 300.00));

        List<Product> allProducts = productRepository.findAll();
        System.out.println("All Products:");
        allProducts.forEach(System.out::println);
    }
}

Updating Existing Data (U)

To update an existing item, you first retrieve it, modify its properties, and then call save() again. Spring Data JPA detects that the entity already has an ID, so it performs an update instead of an insert.

Let's update a product's price:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        Product existingProduct = new Product("Headphones", 150.00);
        productRepository.save(existingProduct);
        System.out.println("Original: " + existingProduct);

        existingProduct.setPrice(120.00); // Update the price
        Product updatedProduct = productRepository.save(existingProduct);
        System.out.println("Updated: " + updatedProduct);
    }
}

Deleting Data by ID (D)

To delete an item, you can use its ID with the deleteById(ID id) method. This is a common way to remove a specific record from the database.

Let's delete a product by its ID:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        Product productToDelete = new Product("Webcam", 50.00);
        productRepository.save(productToDelete);
        System.out.println("Product to delete: " + productToDelete);

        productRepository.deleteById(productToDelete.getId());
        System.out.println("Is product deleted? " + !productRepository.existsById(productToDelete.getId()));
    }
}

Deleting an Entity Object (D)

Alternatively, you can delete an entity by passing the actual entity object to the delete(T entity) method. This is useful if you've already retrieved the object and want to remove it.

Let's delete a product using its object:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Entity
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; }
    @Override
    public String toString() { return "Product{id=" + id + ", name='" + name + "', price=" + price + "}"; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Main.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        Product productToRemove = new Product("Microphone", 80.00);
        productRepository.save(productToRemove);
        System.out.println("Product to remove: " + productToRemove);

        productRepository.delete(productToRemove);
        System.out.println("Is product removed? " + !productRepository.existsById(productToRemove.getId()));
    }
}

Beyond Basic: Derived Query Methods

While findById() and findAll() are great, Spring Data JPA offers even more! You can define custom derived query methods directly in your repository interface.

  • Spring automatically generates the query based on the method name.
  • For example, findByName(String name) will find products by their name.
  • This simplifies common read operations without writing SQL!

We'll explore more complex custom queries in a future lesson.

Quick Check: CRUD Actions

Which of the following Spring Data JPA repository methods are used for reading existing data?

Recap: Mastering CRUD

Congratulations! You've learned how to perform the essential CRUD operations using Spring Data JPA. These methods are the backbone of almost any data-driven application.

  • Create/Update: Use repository.save(entity).
  • Read: Use repository.findById(id) for single items and repository.findAll() for all items.
  • Delete: Use repository.deleteById(id) or repository.delete(entity).

With these powerful repository methods, you can efficiently manage your application's data!

자주 묻는 질문

“CRUD 작업 수행” 강의는 무료인가요?

네 — “CRUD 작업 수행” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

“CRUD 작업 수행”에서 뭘 배우나요?

Spring Data JPA의 강력한 리포지토리 메서드를 사용하여 생성, 조회, 수정, 삭제 작업을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 6번째 강의입니다.

“CRUD 작업 수행” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. H2 데이터베이스 및 JPA 통합
  2. Spring Data JPA 입문
  3. 엔터티 및 리포지터리 만들기
  4. 엔터티 및 리포지토리 정의
  5. REST로 CRUD 작업 구현하기
  6. CRUD 작업 수행
← Spring Boot 4 Microservices & REST APIs(으)로 돌아가기