728x90
상품 Repository 설계
com.shop.repository패키지 생성 후
ItemRepository 인터페이스 생성
package com.shop.repository;
import com.shop.entity.Item;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemRepository extends JpaRepository<Item, Long> {
}
JpaRepository를 상속받는 ItemRepository 작성.
JpaRepository는 2개의 제네릭 타입을 사용하므로 첫 번째에는 엔티티 타입 클래스를 넣고, 두 번째는 기본키 타입을 넣어줍니다.
JpaRepository에는 기본적인 CRUD 및 페이징 처리를 위한 메소드가 정의되어 있습니다.
메소드 | 기능 |
<S extends T> save(S entity) | 엔티티 저장 및 수정 |
void delte(T entity) | 엔티티 삭제 |
count() | 엔티티 총 개수 반환 |
Iterable<T> findAll() | 모든 엔티티 조회 |
테스트 코드 작성
테스트 코드 환경 조성
resources 아래에 application-test.properties파일 생성
# Datasource 설정
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
# H2 데이터베이스 방언 설정
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Junit5를 사용하여 test 폴더에 ItemRepositoryTest.java파일을 생성합니다.
package com.shop.repository;
import com.shop.constant.ItemSellStatus;
import com.shop.entity.Item;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import java.time.LocalDateTime;
@SpringBootTest
@TestPropertySource(locations="classpath:application-test.properties")
class ItemRepositoryTest {
@Autowired
ItemRepository itemRepository;
@Test
@DisplayName("상품 저장 테스트")
public void createItemTest(){
Item item = new Item();
item.setItemNm("테스트 상품");
item.setPrice(10000);
item.setItemDetail("테스트 상품 상세 설명");
item.setItemSellStatus(ItemSellStatus.SELL);
item.setStockNumber(100);
item.setRegTime(LocalDateTime.now());
item.setUpdateTime(LocalDateTime.now());
Item savedItem = itemRepository.save(item);
System.out.println(savedItem.toString());
}
}
실행
insert query문을 따로 작성하지 않고 ItemRepository 인터페이스 작성만으로 상품 테이블에 데이터를 insert할 수 있었던 이유
Spring Data JPA는 인터페이스만 작성하면 런타임 시점에 자바의 Dynamic Proxy를 이용해서 객체를 동적으로 생성.
따로 Data Access Object(Dao)와 xml파일에 쿼리문을 작성하지 않아도 됨.
반응형
'프로젝트 > Archive' 카테고리의 다른 글
[스프링 부트 쇼핑몰 프로젝트 with jpa] Spring DATA JPA Querydsl (0) | 2022.10.04 |
---|---|
[스프링 부트 쇼핑몰 프로젝트 with jpa] @Query 어노테이션 (0) | 2022.09.21 |
[스프링 부트 쇼핑몰 프로젝트 with jpa] 쿼리메소드 (0) | 2022.09.20 |
[스프링 부트 쇼핑몰 프로젝트 with jpa] 상품 엔티티 설계 (0) | 2022.09.18 |
[스프링 부트 쇼핑몰 프로젝트 with jpa] 프로젝트 생성 (0) | 2022.09.16 |