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

엔터티 및 리포지터리 만들기

데이터 모델을 나타내는 JPA 엔터티를 정의하고 데이터 접근에 Spring Data 리포지터리를 사용합니다.

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

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

What are JPA Entities?

Welcome to creating your data model! In Spring Boot with JPA, an Entity is a plain Java object that represents a table in your database.

Think of it as a blueprint for the rows in your table. Each instance of an entity class corresponds to a single row in the database table.

Marking a Class as an Entity

To tell Spring Boot that a Java class is an entity, we use the @Entity annotation. This annotation comes from the Java Persistence API (JPA).

When Spring sees @Entity, it knows to map this class to a database table. By default, the table name will be the same as the class name (e.g., a Product class maps to a Product table).

Defining Primary Keys with @Id

Every database table needs a primary key to uniquely identify each record. In JPA, we mark a field as the primary key using the @Id annotation.

Often, we want the database to automatically generate this ID for us. For this, we use the @GeneratedValue annotation, typically with a strategy like IDENTITY for auto-incrementing numbers.

Our First Product Entity

Let's create a simple Product entity. It will have an ID, a name, and a price. Notice the annotations @Entity, @Id, and @GeneratedValue.

Remember to include a default constructor and getters/setters for JPA to work correctly.

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

    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 +
               '}';
    }
}

Introducing Spring Data Repositories

Now that we have an entity, how do we interact with the database to save, retrieve, update, or delete products? This is where Repositories come in!

Spring Data JPA provides a powerful abstraction that simplifies data access. Instead of writing complex SQL queries, you define simple interfaces.

The JpaRepository Interface

The core of Spring Data JPA is the JpaRepository interface. When your repository interface extends JpaRepository, Spring automatically provides standard CRUD (Create, Read, Update, Delete) methods for your entity.

You just need to specify the entity type and the type of its primary key, like this: JpaRepository<YourEntity, ID_Type>.

Defining Our Product Repository

Let's create a repository for our Product entity. It's just an interface that extends JpaRepository, telling Spring to generate the necessary code for us.

We specify Product as the entity type and Long as the primary key type.

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

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    // Spring Data JPA automatically provides methods like:
    // save(), findById(), findAll(), deleteById(), etc.
}

Using Repositories in Spring

In a Spring Boot application, you would typically inject your repository into a service or controller using @Autowired. Then, you can call the built-in methods.

  • repository.save(product): Saves a new product or updates an existing one.
  • repository.findById(id): Finds a product by its ID.
  • repository.findAll(): Retrieves all products.

Entity & Repository in Action

Here's a conceptual example showing how an entity is created and how a repository would save it. We're simulating the repository behavior to make it runnable without a full Spring Boot setup.

This demonstrates creating a Product object and using a 'save' method.

// --- Simulated Product Entity --- //
class Product {
    private Long id;
    private String name;
    private double price;

    public Product(Long id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    // Getters and Setters (simplified 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 + "}";
    }
}

// --- Simulated Product Repository Interface --- //
interface ProductRepository {
    Product save(Product product);
}

// --- Simulated Product Repository Implementation --- //
class SimpleProductRepository implements ProductRepository {
    private static Long nextId = 1L;
    @Override
    public Product save(Product product) {
        if (product.getId() == null) {
            product.setId(nextId++); // Assign a new ID
        }
        System.out.println("Simulating save: " + product);
        return product;
    }
}

public class Main {
    public static void main(String[] args) {
        // 1. Create a Product entity instance
        Product newProduct = new Product(null, "Wireless Earbuds", 99.99);
        System.out.println("Created product: " + newProduct);

        // 2. Simulate saving it using our repository
        ProductRepository repository = new SimpleProductRepository();
        Product savedProduct = repository.save(newProduct);

        System.out.println("Product after simulated save: " + savedProduct);
    }
}

Quick Check: Core Concepts

Which of the following annotations is used to mark a class as a JPA entity that maps to a database table?

Recap: Entities & Repositories

You've learned the fundamentals of defining your data model with Spring Data JPA!

  • Entities are Java objects representing database tables, marked with @Entity.
  • Primary keys are defined with @Id and often auto-generated using @GeneratedValue.
  • Repositories are interfaces that extend JpaRepository, providing powerful, ready-to-use methods for interacting with your database.

These two concepts are the cornerstone of data persistence in Spring Boot.

자주 묻는 질문

“엔터티 및 리포지터리 만들기” 강의는 무료인가요?

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

“엔터티 및 리포지터리 만들기”에서 뭘 배우나요?

데이터 모델을 나타내는 JPA 엔터티를 정의하고 데이터 접근에 Spring Data 리포지터리를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“엔터티 및 리포지터리 만들기” 강의는 얼마나 걸리나요?

대부분의 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(으)로 돌아가기