티스토리 뷰

Spring Boot 프로젝트에서 JPA를 사용하면 Repository를 통해 DB의 데이터를 꺼내오게 된다.

 

JPA가 지원하는 기본적인 Repository는 다양한 기능을 함께 지원하지만 규모가 커지고 복잡한 쿼리가 필요할때는 한계에 부딪히게 된다. 

 

이럴때 개발자가 자체적으로 Repository를 만들어서 커스텀해 사용해야 하는데 이를 위한 두 가지 방법을 소개하려 한다.

 

1. 기본 Repository에 Interface를 추가하여 확장하는 방법

2. 기본 Repository와 별개의 Repository생성하는 방법

 

1. 추가 Interface를 통해 Repository 확장

 

- 기존 JpaRepostory에 CustomRepo를 추가해준다.

public interface ConsultationRepo extends JpaRepository<Consultation, Long>, 
	ConsultationCustomRepo {
... 중략 ...
}

 

- CustomRepo는 아무것도 상속받지 않은 상태로 구현해줄 메소드들을 정의한다

public interface ConsultationCustomRepo {
  List<Category> findAllCategory();
  ... 중략 ...
}

 

- CustomRepoImpl을 생성하여 CustomRepo interface를 구현해줘야 한다. 여기서 주의할 점은 Impl 접미사를 꼭 붙여줘야 Spring이 알아서 구현체 연결을 해준다.

- Repository 어노테이션도 필수다.

 *configuration변경을 통해 다른 접미사로 변경도 가능하긴 하다.

@Repository
public class ConsultationRepoImpl implements ConsultationCustomRepo {
  @PersistenceContext EntityManager entityManager;

  @Override
  public List<Category> findAllCategory() {
    TypedQuery<Category> query = entityManager.createQuery("select c from Category as c", Category.class);
    return query.getResultList();
  }

  ... 중략 ...
}

 

2. 기본 Repository와 별개의 Repository 구현

 

- 아래와 같이 독립적인 Repository 클레스를 정의하여 생성한다.

이렇게 생성해 줬을때 JpaRepository에 CustomRepo를 다중 상속 받아 구현하는 불편함을 줄일 수 있다.

하지만 save, find..., 와 같은 기본적인 함수를 직접 구현해줘야한다. 

@Repository
public class ConsultationQueryRepo {
  @PersistenceContext EntityManager entityManager;

  public List<Category> findAllCategory() {
    TypedQuery<Category> query = entityManager.createQuery("select c from Category as c", Category.class);
    return query.getResultList();
  }
  
  ... 중략 ...
}

 

정리

 

Jpa를 사용하여 기본으로 제공하는 Repository가 아닌 Custom Repo를 생성하는 두 가지 방법을 알아봤다.

상황에 따라 두 상황 모두 사용하는 방법으로 유연하게 짜는걸 추천하다!

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함