Java Framework/Spring Boot

[Spring Boot] JpaRepository

annovation 2024. 12. 13. 13:51

JpaRepository

Spring Data JPA에서 제공하는 인터페이스로, 데이터베이스와의 CRUD 작업(Create, Read, Update, Delete)을 자동으로 처리합니다.

  • SQL 쿼리를 직접 작성할 필요 없이, 데이터를 더 쉽고 간단하게 처리할 수 있습니다.
  • 데이터베이스와 객체 간의 매핑을 자동화하여 개발 시간을 줄여줍니다.

계층 구조

Spring Data JPA는 다양한 인터페이스 계층을 제공하며, JpaRepository는 이 중 하나입니다.

  1. Repository : 모든 저장소(repository)의 공통 인터페이스
  2. CrudRepository : 기본적인 CRUD(Create, Read, Update, Delete) 작업을 위한 인터페이스
  3. PagingAndSortingRepository : 페이징과 정렬 기능을 추가한 인터페이스
  4. JpaRepository : 페이징, 정렬뿐만 아니라 JPA와 관련된 확장 기능까지 제공하는 인터페이스

사용법

1. Entity 생성

JpaRepository를 사용하려면 먼저 데이터베이스와 매핑될 엔티티(Entity) 클래스를 생성해야 합니다.

ex. 고객 정보를 저장하는 Customer 엔티티

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Customer {
    @Id
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
}

 

 

2. JpaRepository Interface 생성

이제 JPA가 사용할 Repository를 정의합니다. 여기서 중요한 점은 JpaRepository를 상속받는 것만으로 대부분의 데이터 작업을 자동으로 처리할 수 있다는 것입니다.

ex. CustomerRepository 인터페이스 

import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<Customer, Long> {
    // JpaRepository의 기본 기능을 활용
}

➡️ JpaRepository<Customer, Long>

  • 첫 번째 타입(Customer) : 관리할 엔티티 클래스의 이름
  • 두 번째 타입(Long) : 엔티티의 기본 키 타입

➡️ JpaRepository 메서드

  • DB에서 데이터를 가져올 때 해당 테이블의 구조와 일치하는 엔티티 객체로 매핑됨
  • 그래서 repository의 조회 메서드들은 엔티티 타입을 반환

ex. Repository

public interface ClassRepository extends JpaRepository<ClassEntity, Long> {
    // ClassEntity: 엔티티 타입
    // Long: 기본키(ID) 타입
}
  • findById() 메서드는 자동생성됨

ex. Service

@Transactional
    public ClassResponse.EntryResponseData getClassInfo(Long classId) {
        ClassEntity classEntity = classRepository.findById(classId)
              .orElseThrow(() -> new CustomException(ErrorCode.CLASS_NOT_FOUND));

        return ClassResponse.EntryResponseData.from(classEntity);
    }

 

  • repository의 조회 메서드들은 엔티티 타입을 반환하므로 엔티티 타입의 변수에 담아줘야한다.

기본 Method

JpaRepository를 상속받으면 기본적으로 사용할 수 있는 메서드들이 있습니다.

1. CRUD

  • save(T entity) : 엔티티를 데이터베이스에 저장하거나 업데이트
  • findById(ID id) : 기본 키로 데이터 조회
  • findAll() : 모든 데이터 조회
  • deleteById(ID id) : 기본 키로 데이터 삭제
  • count() : 총 데이터 개수 반환

ex. 데이터를 저장하고 조회하는 코드

@Autowired
private CustomerRepository customerRepository;

public void saveAndFindCustomer() {
    // 저장
    Customer customer = new Customer();
    customer.setId(1L);
    customer.setName("John Doe");
    customer.setEmail("john.doe@example.com");
    customerRepository.save(customer);

    // 조회
    Customer foundCustomer = customerRepository.findById(1L).orElse(null);
    System.out.println(foundCustomer.getName());
}

 

2. 페이징과 정렬

  • 페이징 : 데이터를 페이지 단위로 나누어 조회
    • Page<T> findAll(Pageable pageable)
  • 정렬 : 특정 속성을 기준으로 정렬
    • List<T> findAll(Sort sort)

ex. 이름을 기준으로 정렬된 고객 목록 조회

List<Customer> sortedCustomers = customerRepository.findAll(Sort.by("name"));

Custom Query

Spring Data JPA는 이름 기반으로 메서드를 작성하면 자동으로 쿼리를 생성해줍니다.

1. Method 이름으로 Query 생성

 

(1) 메서드 이름만으로 조건을 설정할 수 있습니다.

ex. 이메일로 고객을 조회하는 메서드

List<Customer> findByEmail(String email);

 

(2) Spring Data JPA는 메서드 이름을 분석해 자동으로 SQL 쿼리를 생성합니다.

위 메서드는 SQL로 변환되면 다음과 같습니다.

SELECT * FROM customer WHERE email = ?;

 

2. @Query Annotation

복잡한 쿼리가 필요할 경우, 직접 SQL 또는 JPQL(JPA Query Language)을 작성할 수 있습니다.

ex. 이름에 "John"이 포함된 고객 조회 

@Query("SELECT c FROM Customer c WHERE c.name LIKE %:name%")
List<Customer> findByNameContaining(@Param("name") String name);

출처

OpenAI ChatGPT (https://openai.com)

반응형