Repository란?
“DB 접근 담당 계층”
Repository는 데이터 접근 전략을 담당한다.
(fetch join, paging, query 최적화 등)
프로젝트 구현
package com.example.crudproject.repository;
import com.example.crudproject.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
package com.example.crudproject.repository;
import com.example.crudproject.entity.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("""
select o
from Order o
join fetch o.product
""")
List<Order> findAllWithProduct();
}
코드 설명
public interface ProductRepository extends JpaRepository<Product, Long>
class가 아니라 interface인 이유 : JPA가 구현체를 자동 생성하기 때문!
extends JpaRepository, Long> 로 인해 아래와 같은 메서드가 자동으로 생성됨
- save() : INSERT or UPDATE
- findById() : select * from products where id = ()
- findAll() : select * from products
- deleteById() : delete from products where id = 1
@Query("""
select o
from Order o
join fetch o.product
""")
List<Order> findAllWithProduct();
findAll()을 사용하면 발생하는 N+1 문제 해결을 위해 join fetch를 적용해 새로 메서드 정의
'Spring > - [시리즈] 간단한 CRUD 구현하기' 카테고리의 다른 글
| CRUD 구현 6 - Service 구현 (0) | 2026.05.15 |
|---|---|
| CRUD 구현 5 - DTO (Data Transfer Object) 구현 (0) | 2026.05.15 |
| CRUD 구현 3 - Entity 구현 (0) | 2026.05.14 |
| CRUD 구현 2 - DB 세팅 및 ERD (mySql, JPA) (0) | 2026.05.12 |
| CRUD 구현 1 - 요구 사항 및 개발 환경 (0) | 2026.05.12 |