Persistence Layer ํ ์คํธ
Repository ํ ์คํธ๋ฅผ ์ ํด์ผํ ๊น?
1. JPA ๋ฉ์๋๊ฐ ์์ฑ์์ ์๋๋๋ก ์ฟผ๋ฆฌ๋ฅผ ์์ฑํ๊ณ ์คํํ๋์ง ๊ฒ์ฆํ๊ธฐ ์ํด
๊ฐ๋ฐ์๋ ์ฝ๋์ ๊ธฐ๋ฐํ ๋ก์ง์ด ์ฌ๋ฐ๋ฅด๊ฒ ์๋ํ๋ค๊ณ ๋ฏฟ์ ์ ์์ง๋ง, ์ค์ ๋ก ์์ฑ๋ ์ฟผ๋ฆฌ๊ฐ ๊ธฐ๋์ ๋ค๋ฅผ ์ ์๋ค!
2. ๋ฏธ๋์ ๋ณ๊ฒฝ ์ฌํญ์ ๋๋นํ๊ธฐ ์ํด
ํ์ฌ JPA๋ฅผ ์ฌ์ฉํ๋๋ผ๋ ํฅํ QueryDSL, MyBatis์ ๊ฐ์ ๋ค๋ฅธ ๊ธฐ์ ๋ก ๋ณ๊ฒฝ๋ ๊ฐ๋ฅ์ฑ์ด ์๋ค. Repository ํ ์คํธ๋ฅผ ์ ๊ตฌ์ฑํด ๋๋ฉด, ์ด๋ฌํ ๋ณ๊ฒฝ์๋ ์์ ์ ์ผ๋ก ๋์์ ๊ฒ์ฆํ ์ ์๋ค.
Repository ์ฝ๋
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
/**
* select *
* from product
* where selling_status in ('SELLING', 'HOLD');
*/
List<Product> findAllBySellingStatusIn(List<ProductSellingStatus> sellingStatuses);
}
RepositoryTest ์ฝ๋
ํ ์คํธ ์ฝ๋์์ ๋ฆฌ์คํธ๋ฅผ ๊ฒ์ฆํ ๋, ์๋ ๋ฉ์๋๋ค์ ์กฐํฉํ๋ฉด ๊ฐ๋ ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ๋์ผ ์ ์๋ค.
โ `.hasSize` : ๋ฆฌ์คํธ์ ํฌ๊ธฐ๋ฅผ ๊ฒ์ฆํ๋ค.
โ `.extracting` : ๋ฆฌ์คํธ ๋ด ๊ฐ์ฒด์์ ํน์ ํ๋๋ฅผ ์ถ์ถํ์ฌ ๊ฒ์ฆํ๋ค.
โ `.containsExactlyInAnyOrder` : ๋ฆฌ์คํธ์ ํน์ ๊ฐ๋ค์ด ๋ชจ๋ ํฌํจ๋์ด ์๋์ง ๊ฒ์ฆํ๋ค. (์์์ ์๊ด ์์)
assertThat(products).hasSize(2)
.extracting("productNumber", "name", "sellingStatus")
.containsExactlyInAnyOrder(
tuple("001", "์๋ฉ๋ฆฌ์นด๋
ธ", SELLING),
tuple("002", "์นดํ๋ผ๋ผ", HOLD)
);
์ ์ฒด ์ฝ๋
@ActiveProfiles("test")
//@SpringBootTest
@DataJpaTest
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@DisplayName("์ํ๋ ํ๋งค์ํ๋ฅผ ๊ฐ์ง ์ํ๋ค์ ์กฐํํ๋ค.")
@Test
void findAllBySellingStatusIn() {
// given
Product product1 = Product.builder()
.productNumber("001")
.type(HANDMADE)
.sellingStatus(SELLING)
.name("์๋ฉ๋ฆฌ์นด๋
ธ")
.price(4000)
.build();
Product product2 = Product.builder()
.productNumber("002")
.type(HANDMADE)
.sellingStatus(HOLD)
.name("์นดํ๋ผ๋ผ")
.price(4500)
.build();
Product product3 = Product.builder()
.productNumber("003")
.type(HANDMADE)
.sellingStatus(STOP_SELLING)
.name("ํฅ๋น์")
.price(7000)
.build();
productRepository.saveAll(List.of(product1, product2, product3));
// when
List<Product> products = productRepository.findAllBySellingStatusIn(List.of(SELLING, HOLD));
// then
assertThat(products).hasSize(2)
.extracting("productNumber", "name", "sellingStatus")
.containsExactlyInAnyOrder(
tuple("001", "์๋ฉ๋ฆฌ์นด๋
ธ", SELLING),
tuple("002", "์นดํ๋ผ๋ผ", HOLD)
);
}
}