JPA์์ ์ํฐํฐ๋ฅผ ์์ฑํ ๋ Wrapper class๋ฅผ ์ฌ์ฉํด์ผํ ๊น primitive type์ ์ฌ์ฉํด์ผํ ๊น?
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int stock; // Integer? int?
}
๋ค์ ์ํฉ์์ stock์ int๋ก ์์ฑํด์ผ๋ ๊น Integer๋ก ์์ฑํด์ผ๋ ๊น?
1. primitive type & Wrapper Class
์์ ํ์ (primitive type)
โ Java์์ ๊ธฐ๋ณธ์ผ๋ก ์ ๊ณต๋๋ ๋ฐ์ดํฐ ํ์
โ int, byte, short, long, float, double, boolean, char
โ ์ฅ์
- ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋์ด ์ ๋ค. (์คํ ์์ญ์ ๋ฐ๋ก ์์ฑ)
- ์ฑ๋ฅ์ด ์ข๋ค.
โ ๋จ์
- โญnull ๊ฐ์ ํ์ฉํ์ง ์๋๋ค. (NPE ๋ฐ์)
๋ํผ ํด๋์ค(wrapper ํด๋์ค)
โ ์์ ํ์ ์ ๊ฐ์ฒด๋ก ๊ฐ์ธ์ ์ฌ์ฉํ ์ ์๋๋ก ํด์ฃผ๋ ํด๋์ค
โ Integer, Long, Float, Double, Boolean ๋ฑ
โ ์ฅ์
- โญnull ๊ฐ์ ํ์ฉํ๋ค
- ๋ค์ํ ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ค
โ ๋จ์
- ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋์ด ํฌ๋ค
- ์ฑ๋ฅ์ด ๋ค์ ๋จ์ด์ง๋ค(๋ฐ์ฑ, ์ธ๋ฐ์ฑ)
2. JPA์์๋ ๋ญ ์ฌ์ฉํด์ผ๋ ๊น?
โ JPA์์๋ ์ผ๋ฐ์ ์ผ๋ก Wrapper ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ๊ถ์ฅ๋๊ณ Hibernates์ ๊ณต์ ๋ฌธ์์์๋ ํนํ ID์ ๊ฒฝ์ฐ์ Nullableํ ์๋ฃํ(Wrapper)๋ฅผ ์ฌ์ฉํ ๊ฒ์ ๊ถ์ฅํ๊ณ ์๋ค

โ ๊ฐ์ฅ ํฐ ์ด์ ๋ db์์ Null๊ฐ ํ์ฉ์ ํตํด์ ์ป๋ ์ด์ ์ด ํฌ๋ค๋ ๊ฒ์ด๋ค.
โ ๋ํ ๋ฐ์ฑ/์ธ๋ฐ์ฑ์ด๋, ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋ ๋ฑ ์ฑ๋ฅ์์ ๋จ์ ์ญ์ ์ปดํจํ ์ฑ๋ฅ์ ํฅ์์ผ๋ก ์ธํด ํฐ ์ํฅ์ ๋ฏธ์น์ง ์์ ์ ๋๊ฐ ๋์๋ค.
- NULL ๊ฐ ํ์ฉ: Wrapper Class๋ NULL ๊ฐ์ ํ์ฉํ๋ฏ๋ก, ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ํด๋น ์ปฌ๋ผ์ด NULL ๊ฐ์ ๊ฐ์ง ์ ์๋ ๊ฒฝ์ฐ Wrapper Class๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ ์ ํ๋ค
- Optional์ ํตํ ์์ ํ NULL ์ฒ๋ฆฌ: JPA๋
Optional
์ ํตํ Null ๊ฐ ์ฒ๋ฆฌ๋ฅผ ์ ๊ทน์ ์ผ๋ก ์ง์ํ๋ฏ๋ก primitive type์์ NPE๊ฐ ์๋ ์๋น์ค์ ๋ง๊ฒ null ๊ฐ์ ์ ์ ํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋ค.
public interface ProductRepository extends JpaRepository<Product, Long> {
Optional<Product> findById(Long id);
}
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
// optional์ ํ์ฉํด ์ํฉ์ ๋ง๊ฒ ์๋ฌ๋ฅผ ์ฒ๋ฆฌํ ์ ์๋ค.
public Product getProductById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException("Product not found with id: " + id));
}
}
๊ฒฐ๋ก
โ ์ผ๋ฐ์ ์ธ ์ํฉ์์๋ Null ๊ฐ ํ์ฉ์ด ๊ฐ์ ธ์ค๋ ์ด์ ์ด ์ปค์ Wrapper ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ ๋ฆฌํ๋ค.
โ ๊ทธ๋ฌ๋ ์ฑ๋ฅ์ด ํนํ ์ค์ํ๋ฉฐ, db์์ ํด๋น ์์ฑ์ ๋ํด ํญ์ ๊ฐ์ด ์กด์ฌํจ์ด ๋ณด์ฅ๋ ๊ฒฝ์ฐ primitive type์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ ๋ฆฌํ ์๋ ์๋ค.
'โญ Personal_Study > Spring' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์น์์ผ์ ํ์ฉํด ์ค์๊ฐ ์ฑํ ๊ตฌํํ๊ธฐ - Spring (2) | 2023.04.23 |
---|---|
Page ๊ฐ์ฒด์ Collections ๋ฉ์๋๋ฅผ ์ ์ฉํ์ ๋ UnsupportedOperationException ๋ฐ์ ์๋ฌ (0) | 2023.03.30 |
๋น ์๋ช ์ฃผ๊ธฐ ์ฝ๋ฐฑ (0) | 2023.01.10 |
์์กด๊ด๊ณ ์๋ ์ฃผ์ (1) | 2023.01.09 |
ComponentScan (0) | 2023.01.07 |
๋๊ธ