본문 바로가기

ys TIL

Spring Boot Data Jpa 사용자 정의 Repository 만들기

스프링 데이터 JPA 리포지토리는 인터페이스만 정의하고 구현을 스프링이 하기 때문에 인터페이스의 직접 메서드를 구현하고 싶을 때 스프링 데이터 JPA가 제공하는 인터페이스의 많은 기능을 직접 구현해야한다. 따라서 사용자 정의 리포지토리를 사용해 스프링 데이터 JPA 리포지토리 인터페이스에서 querydsl을 사용해보자

 

PersonRepository

public interface PersonRepository extends JpaRepository<Person,Long> {

}

1. PersonRepositoryCustom 인터페이스를 만든다

public interface PersonRepositoryCustom {
    List<Person> findAllPersonCustom();
}

 

2. PersonRepositoryImpl을 만들고 PersonRepositoryCustom 을 구현한다.

@RequiredArgsConstructor
public class PersonRepositoryImpl implements PersonRepositoryCustom {

    private final  JPAQueryFactory queryFactory;

    @Override
    public List<Person> findAllPersonCustom() {
        List<Person> people = queryFactory.select(person)
                .from(person)
                .fetch();
        return people;
    }
}

 

3. PersonRepositoryCustom를 PersonRepository가 상속하도록 한다.

public interface PersonRepository extends JpaRepository<Person,Long>, PersonRepositoryCustom{

}

 

주의할 점

사용자 정의 구현 클래스의 이름은 리포지토리 이름 +Impl

예) PersonRepository => PersonRepositoryImpl

 

'ys TIL' 카테고리의 다른 글

querydsl 적용하기  (0) 2020.07.10
Spring 외부 설정 파일  (0) 2020.07.10
Spring Boot test에서 H2 In memory 설정하기  (0) 2020.06.02