본문 바로가기

카테고리 없음

[스프링] 스프링 핵심 3 - JPA

0. JPA가 모얌?

ProductRepository.java : 

public interface ProductRepository extends JpaRepository<Product, Long> { }

applicaton.properties : 

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:springcoredb
spring.datasource.username=sa
spring.datasource.password=

Bean을 등록해줄 필요 없이 application.properties에 접속할 데이터 베이스 정보를 명시하면 JPA는 자동으로 DB에 접속을 해줍니다. SimpleJpaRepository<T, ID>는 JpaRepository<T, ID>를 내부적으로 구현합니다. SimpleRepository에 명시된 @Repository 어노테이션에서 볼 수 있듯이 JPA는 컴포넌트로 등록되어 필요할 때마다 생성자 주입을 받을 수 있습니다. 

이제 Repository를 생성자 주입을 받은 Service 객체가 어떤 식으로 JPA를 사용하는지 보도록 하겠습니다.

@Service
public class ProductService {
    private final ProductRepository productRespository;

    public Product updateProduct(Long id, ProductMypriceRequestDto requestDto) throws SQLException {
        Product product = productRepository.findById(id)
                .orElseThrow(() -> new NullPointerException("해당 아이디가 존재하지 않습니다."));

    //...
    }
}

productRepository.findById(id) 함수를 통해 DB에서 id 값에 해당하는 Product 객체를 가져옵니다. 또한 findById() 는 Optional Wrapper가 적용되어 있기 때문에 Optional<T>객체로 결과를 받거나 .orElseThrow() 으로 throw 처리를 해줍니다. throw 처리는 만약 id에 해당하는 entity가 존재하지 않을  경우 NPE를 처리를 해주게 됩니다.