엔터티 및 리포지토리 정의
데이터베이스 테이블에 매핑할 JPA 엔터티를 만들고 데이터 접근을 위한 리포지토리 인터페이스를 정의합니다.
엔터티 및 리포지토리 정의은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 6개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Welcome to Data Persistence
In this lesson, we'll learn how to connect your Java application to a database using Spring Boot. This is called data persistence, meaning your data lives on even after your app stops.
We'll focus on two core concepts:
- Entities: Your Java objects that map to database tables.
- Repositories: Interfaces that provide easy ways to interact with your entities and the database.
What's a JPA Entity?
A JPA Entity is a plain Java class that represents a table in your relational database. Each instance of this class corresponds to a row in that table.
The Java Persistence API (JPA) is a standard for managing relational data in Java applications. Spring Data JPA builds on this to simplify database interactions even further.
Defining Your First Entity
To mark a Java class as a JPA Entity, you use the @Entity annotation. You also need to define a primary key using @Id.
Let's create a simple Product entity:
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
private Long id;
private String name;
private double price;
public Product() {}
public Product(Long id, String name, double price) {
this.id = id;
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 + "}";
}
public static void main(String[] args) {
Product product = new Product(1L, "Laptop", 1200.00);
System.out.println(product);
}
}Auto-Generating Primary Keys
Manually assigning IDs can be tedious and prone to errors. Databases can automatically generate unique IDs for you!
Use the @GeneratedValue annotation along with a strategy. GenerationType.IDENTITY is common for databases that auto-increment (like MySQL, H2).
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@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) { // No ID in constructor
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 + "}";
}
public static void main(String[] args) {
Product product = new Product("Keyboard", 75.00);
// In a real app, ID would be generated by the DB when persisted
System.out.println("Product created (ID will be generated by DB): " + product);
}
}Customizing Column Mappings
By default, JPA maps fields to columns with the same name. You can customize this using the @Column annotation.
It lets you specify the column name, whether it's nullable, its length, and more:
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "product_name", nullable = false, length = 100)
private String name;
@Column(nullable = false)
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 + "}";
}
public static void main(String[] args) {
Product product = new Product("Mouse", 25.50);
System.out.println("Product with custom columns: " + product);
}
}Introducing Spring Data Repositories
Now that we have an entity, how do we save it to the database or retrieve it? That's where Spring Data Repositories come in!
A repository is an interface that provides powerful, pre-built methods for common database operations (like Create, Read, Update, Delete - CRUD). You don't write SQL; Spring Data JPA generates it for you.
Defining a JpaRepository Interface
To create a repository for your entity, you simply define an interface that extends Spring Data JPA's JpaRepository.
The JpaRepository takes two type parameters: the Entity type and the type of its Primary Key.
Here's how you'd define a repository for our Product entity:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// Assuming 'Product' entity is defined in the same package or imported
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Spring Data JPA automatically provides CRUD methods here!
// You can add custom query methods if needed, e.g.,
// List<Product> findByName(String name);
}Note: The @Repository annotation is optional but good practice for clarity.
Built-in Repository Methods
By extending JpaRepository, your ProductRepository automatically inherits many powerful methods. Here are a few:
save(entity): Saves a given entity (inserts if new, updates if exists).findById(id): Retrieves an entity by its ID, returning anOptional.findAll(): Returns all instances of the entity type.delete(entity)ordeleteById(id): Removes an entity.
This means you get full CRUD functionality without writing a single line of implementation code!
Using Repositories in an App
In a real Spring Boot application, you would inject your repository into a service or controller using @Autowired and then call its methods.
While we can't run a full Spring Boot app with a database here, this snippet shows the conceptual usage within a typical Spring Boot component:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
// Assuming Product and ProductRepository are defined
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Product createProduct(String name, double price) {
Product newProduct = new Product(name, price);
return productRepository.save(newProduct);
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
}
This ProductService would then be used by other parts of your application.
Quick Check on Entities
Which of the following annotations are essential for defining a basic JPA Entity that maps to a database table and has an auto-generated primary key?
Recap: Entities & Repositories
Great job! You've learned the foundations of data persistence with Spring Data JPA:
- Entities are Java classes annotated with
@Entitythat map to database tables. @Idmarks the primary key, and@GeneratedValuelets the database handle ID generation.@Columnallows you to customize field-to-column mappings.- Repositories are interfaces that extend
JpaRepository<Entity, ID>, providing powerful, ready-to-use CRUD methods without writing SQL.
Next, you'll dive deeper into performing various CRUD operations!
AI 튜터와 함께 Java을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 24
- 레슨
- 93
자주 묻는 질문
“엔터티 및 리포지토리 정의” 강의는 무료인가요?
네 — “엔터티 및 리포지토리 정의” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.
“엔터티 및 리포지토리 정의”에서 뭘 배우나요?
데이터베이스 테이블에 매핑할 JPA 엔터티를 만들고 데이터 접근을 위한 리포지토리 인터페이스를 정의합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 4번째 강의입니다.
“엔터티 및 리포지토리 정의” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.