본문 바로가기

개발 재활기

개발새발 개발 재활기 - 게시판 프로젝트(3)

REPOSITORY 작성

저번 시간에는 Entity를 작성하고 끝냈다. 이번 시간에는 Repository를 작성해볼 것이다. Repository는 Spring Data JPA를 활용하여 작성하기로 했다.

 

1) Spring Data JPA란?

Spring Data JPA는 Spring Framework에서 제공하는 데이터 접근 기술로, JPA(Java Persistence API)를 기반으로 반복적인 CRUD 코드의 생략표준화된 인터페이스를 통해 생산성과 유지보수성을 극대화하는 기술이다. 따라서 Interface 만 작성하고, JpaRepository를 상속받으면 Repository를 따로 구현할 필요가 없다.

 

2) 프로젝트 설정

1) 의존성 추가

게시판 프로젝트(1) 편에서 프로젝트 파일을 생성할 때 dependencies에 Spring Data JPA를 추가했었다. 그러면 build.gradle에 

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

라는 의존성이 추가가 된다. 이제 외부 라이브러리에 JPA가 추가되었으므로, 프로젝트 내에서 Spring Data JPA를 사용할 수 있다.

 

2) application.yml 설정

spring:
  h2:
    console:
      enabled: true
    datasource :
      url : jdbc:h2:tcp://localhost/~/spring-project/board
      username : sa
      password :
      driver-class-name : org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        format_sql: true

이전 게시글들에서 위와 같이 application.yml을 설정해주었다. 이번에는 표로 각각 설정들이 뭘 의미하는지만 보고 넘어가자.

설정 설명
ddl-auto 스키마 자동 생성/수정 방식
show-sql 실행되는 SQL 출력
format-sql SQL을 보기 좋게 포맷팅
driver-class-name H2 드라이버 클래스 지정
옵션 설명
none 스키마 자동 변경 안함 (운영시 사용)
update 변경 사항만 반영 (개발용)
create 매번 새로 생성
create-drop 종료시 제거 (테스트용)

 

3) Repository 작성

Repository를 만들 때, class가 아닌 interface이다. 헷갈리지 않게 주의하자.

//게시판 Repository
public interface PostRepository extends JpaRepository<Post, UUID> {
}

//댓글 Repository
public interface CommentRepository extends JpaRepository<Comment, UUID> {
}

//사용자 Repository
public interface UserRepository extends JpaRepository<User, UUID> {
}

 

Spring Data JPA의 Repository는 아래 보이는 것처럼 계층적으로 구성되어 있다

Repository (Marker Interface)
    ├─ CrudRepository<T, ID>
    │   ├─ save(), findById(), deleteById() ...
    │
    ├─ PagingAndSortingRepository<T, ID>
    │   ├─ 페이징, 정렬 기능 제공
    │
    └─ JpaRepository<T, ID>
        ├─ CRUD + 페이징 + JPA 확장 기능

이를 표로 정리하자면,

인터페이스 기능 주의사항
Repository 마커 인터페이스 기능 없음, 인식용
CrudRepository CRUD (생성, 조회, 수정, 삭제) 기본적인 Entity 관리
PagingAndSortingRepository 페이징, 정렬 Pageable, Sort 지원
JpaRepository CRUD + 페이징 + Batch, Flush 가장 널리 사용됨

이와 같다. JpaRepository가 대부분의 기능을 가지고 있기 때문에 실무에서는 대부분 JpaRepository를 사용한다.

JpaRepository가 가지고 있는 메서드 종류로는 아래와 같은 종류들이 있으며, 해당 메서드들은 따로 작성을 하지 않아도 자동으로 생성이 된다. 또한, 메서드 이름을 기반으로 자동으로 쿼리 생성이 가능하다.

  1. CRUD 메서드
    • count
    • delete, deleteAll, deleteAllById, deleteById
    • findById
    • save, existsById 등
  2. List CRUD 메서드
    • findAll
    • findAllById
    • saveAll
  3. Query Creation 메서드
    • findOne
    • findAll
    • findBy
    • exists
    • count
  4. 영속성 컨텍스트 관련 메서드
    • flush()
    • saveAndFlush
    • deleteAllInBatch

등이 있으며, 자세한 내용은 아래 사이트에서 확인이 가능하다.

[Spring DOCS : JpaRepository] https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html

 

JpaRepository (Spring Data JPA Parent 4.1.0 API)

Deletes the given entities in a batch which means it will create a single query. This kind of operation leaves JPAs first level cache and the database out of sync. Consider flushing the EntityManager before calling this method. It will also NOT honor casca

docs.spring.io

 

우선은, 어떤 Query를 어떻게 사용할지 모르니 기본적인 Repository만 만들어두고, Service를 개발함에 따라 Repository를 추가 개발하기로 했다. 다음 시간에는 Service를 개발해 볼 것이다.