본문 바로가기
Spring

[Spring Data JPA] Custom Repository - 사용자 정의 리포지토리

by 개미가되고싶은사람 2025. 1. 13.

Spring Data JPA를 사용하면 인터페이스만 정의해도 Spring이 환경 설정 파일을 기반으로 데이터 접근 기술의 구현체를 자동으로 생성해줍니다. 하지만 만약 Spring이 제공하는 구현체가 아닌 다른 데이터 접근 기술을 사용하고 싶다면 어떻게 하는지 알아보겠습니다.

 

CustomRepository

JPA, JDBC, 데이터 접근 기술, Querydsl 다양한 데이터 접근 기술로 사용자 정의 Repository를 생성할 수 있습니다. 필자는 JPA를 이용해서 간단하게 Custom 인터페이스를 구현해보겠습니다.

 

1. 사용자 정의 인터페이스 작성 

사용자 정의 Repository를 위해서 먼저 사용자 정의 인터페이스를 작성합니다.

public interface MemberRepositoryCustom {
    List<Member> findMemberCustom();
}

 

2. 사용자 정의 인터페이스 구현체 구현

// 2. 사용자 정의 인터페이스 구현체 구현
@RequiredArgsConstructor
public class MemberRepositoryImpl implements MemberRepositoryCustom {

    private final EntityManager em;

    @Override
    public List<Member> findMemberCustom() {
        return em.createQuery("select m from Member m", Member.class)
                .getResultList();
    }
}

인터페이스를 작성했으니 이제 구현체를 작성하면 됩니다. 이때 클래스 네이밍 규칙이 있습니다.

  • 2.x 이전 버전: JpaRepository를 상속받고 있는 레포지토리의 이름 + Impl
  • 2.x 이후 버전: JpaRepository를 상속하고 있는 레포지토리의 이름 + Impl, 사용자 정의 인터페이스의 이름 + Impl 

예를 들어서 MemberRepositoryImpl 대신에 MemberRepositoryCustomImpl으로 파일을 생성해도 됩니다.

 

3. 사용자 정의 인터페이스 적용 

이제 사용자 정의 Repository를 사용하려면 사용하고 싶은 사용자 정의 인터페이스를 상속받도록 합니다.

@Test
public void customRepository() {
	List<Member> members = memberRepository.findMemberCustom();

    boolean isCustomRepository = memberRepository instanceof MemberRepositoryCustom;
    Assertions.assertThat(isCustomRepository);
}

해당 테스트를 통해 사용자 정의 Reposiroy가 사용된 지 확인 할 수 있습니다.

 

 

주의사항

사용자 정의 레포지토리를 사용할 때 주의해야 할 두 가지 주요 사항은 다음과 같습니다:

 

1. 명확한 사용 목적

사용자 정의 레포지토리를 도입할 때는 그 필요성이 분명해야 합니다. 예를 들어, 두 개의 레포지토리 A와 B가 있다고 가정해봅시다.

A 레포지토리: 복잡한 쿼리를 통해 화면에 표시할 데이터를 조회하는 역할
B 레포지토리: 비즈니스 로직을 처리하며, 기본적인 CRUD 기능을 제공하는 JpaRepository를 상속받음.
이 경우, A 레포지토리를 사용자 정의 레포지토리로 만들고 B 레포지토리가 A 레포지토리를 상속받는다면, 다음과 같은 문제가 발생할 수 있습니다:

A 레포지토리와 B 레포지토리는 서로 다른 클래스 파일로 존재하지만, A 레포지토리에 접근하기 위해서는 B 레포지토리를 거쳐야 합니다. 이는 두 레포지토리 간의 완전한 분리를 방해합니다.


2. 독립적인 Bean 등록

A 레포지토리와 B 레포지토리를 각각 독립적인 Bean으로 등록하여 필요한 곳에서 독립적으로 사용할 수 있도록 설계해야 하며, 이를 통해 코드의 가독성과 유지보수성을 향상시키고, 커맨드와 쿼리를 분리하여 CQRS 원칙을 지킬 수 있습니다.

 

 

 

참고자료

https://imprint.tistory.com/142

 

[Spring Data JPA] Custom Repository

이번 장에서는 사용자 정의 레포지토리에 대해서 알아본다. 글의 하단부에 참고한 강의와 공식문서의 경로를 첨부하였으므로 자세한 사항은 강의나 공식문서에서 확인한다. 모든 코드는 깃허

imprint.tistory.com

https://docs.spring.io/spring-data/jpa/reference/repositories/custom-implementations.html

 

Custom Repository Implementations :: Spring Data JPA

The approach described in the preceding section requires customization of each repository interfaces when you want to customize the base repository behavior so that all repositories are affected. To instead change behavior for all repositories, you can cre

docs.spring.io

https://docs.spring.io/spring-data/commons/docs/1.9.0.RELEASE/reference/html/#repositories.single-repository-behaviour:~:text=query%20method%20functionality.-,2.6.1.%20Adding%20custom%20behavior%20to%20single%20repositories,-To%20enrich%20a

 

Spring Data Commons - Reference Documentation

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. Spring Data repository documentation and your module This chapter explains the

docs.spring.io