SpringBoot with JPA 페이징/정렬처리

mingki·2022년 1월 27일
1

SpringBoot & JPA

목록 보기
7/26


📚 공부한 책 : 코드로배우는 스프링 부트 웹프로젝트

1.페이징 처리에 사용하는 메서드

JPA 는 개발자들이 SQL이 아닌 API의 객체와 메서드를 사용하는 형태로 페이징 처리를 할 수 있도록 도와준다

  • 페이징 처리와 정렬에 사용하는 메서드 : findAll()
    findAll()메소드는 ]paRepository 인터페이스의 상위인 PagingAndSortRepository의 메서드로 파라미터로 전달되는 Pageable이라는 타입의 객체에 의해서 실행되는 쿼리를 결정하게 된다

2.페이징 처리에 사용하는 인터페이스

페이징 처리를 위한 가장 중요한 것은 org.springframework.data.domain.Pageable 인터페이스이다

  • Pageable 인터페이스는 페이지 처리에 필요한 정보를 전달하는 용도의 타입으로 인터페이스이기 때문에 실제 객체를 생성할 때는 구현체인 PageRequest라는 클래스를 사용한다
    -> PageRequest 클래스의 생성자는 protected로 선언되어 new를 사용할수 없고 객체를 생성하기 위해서는 static한 of()를 이용해 처리한다

3.페이징처리 테스트 코드

아래 코드에서 주의 깊게 볼 부문중 하나는 리턴타입이 Page라는 점이다
-> Page타입은 단순히 해당 목록만으로 가져오는데 그치지 않고 실제 페이지 처리에 필요한 전체 데이터의 개수를 가져오는 쿼리도 같이 처리하기 때문이다

import com.example.entity.Memo;
import com.example.repository.MemoRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;


@SpringBootTest
public class MemberRepositoryTest {

    @Autowired
    MemoRepository memoRepository;

    @Test
    public void testPageDefault(){

        // 1페이지 10개
        Pageable pageable = PageRequest.of(0,10);

        Page<Memo> result = memoRepository.findAll(pageable);

        System.out.println(result);

    }
}

☀︎ 위의 테스트 코드를 실행하면 아래와 같은 SQL이 실행된다

findAll()에 Pageable타입의 파라미터를 전달하면 페이징 처리에 관련된 쿼리들을 실행하고, 이 결과들을 이용해 리턴타입으로 지정된 Page<엔티티타입>객체로 저장한다

Hibernate: 
    select
        memo0_.mno as mno1_0_,
        memo0_.memo_text as memo_tex2_0_ 
    from
    	// limit : MySql에서 페이징 처리에 사용하는 limit구문 
        tbl_memo memo0_ limit ?
Hibernate: 
    select
    	// count() : 전체 개수를 처리한다
        count(memo0_.mno) as col_0_0_ 
    from
        tbl_memo memo0_
Page 1 of 10 containing com.example.entity.Memo instances

4. 정렬 테스트 코드

페이징 처리를 담당하는 PageRequest에는 정렬과 관련된 Sort타입을 파라미터로 전달할 수 있다
-> Sort는 한 개 , 여러개의 필드값을 이용해 순차정렬(asc)나 역순정렬(desc)을 지정할 수 있다
또한 Sort의 and()를 이용해 여러 개의 정렬 조건을 다르게 지정할 수 있다

import com.example.entity.Memo;
import com.example.repository.MemoRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;


@SpringBootTest
public class MemberRepositoryTest {

    @Autowired
    MemoRepository memoRepository;

    @Test
    public void testPageDefault(){

         // 정렬
        Sort sort = Sort.by("mno").descending();
        
        Sort sort2 = Sort.by("memoText").ascending();
        
        Sort sortAll = sort.and(sort2); // and를 이용한 연결
        
    
        // 1페이지 10개
        Pageable pageable = PageRequest.of(0,10,sort);

        Pageable pageable2 = PageRequest.of(0,10,sortAll);

        Page<Memo> result = memoRepository.findAll(pageable);

        Page<Memo> result2 = memoRepository.findAll(pageable2);

        System.out.println(result);

        result.get().forEach(memo -> {
            System.out.println(memo);
        });

        System.out.println(result2);
        result2.get().forEach(memo -> {
            System.out.println(memo);
        });

    }
}

☀︎ 위의 페이징 쿼리와 달리 order by 가 사용된것을 확인 할 수 있다

Hibernate: 
    select
        memo0_.mno as mno1_0_,
        memo0_.memo_text as memo_tex2_0_ 
    from
        tbl_memo memo0_ 
    order by
        memo0_.mno desc limit ?
Hibernate: 
    select
        count(memo0_.mno) as col_0_0_ 
    from
        tbl_memo memo0_
Page 1 of 10 containing com.example.entity.Memo instances
---------------------------------------------------------------
// and 사용한 쿼리
Hibernate: 
    select
        memo0_.mno as mno1_0_,
        memo0_.memo_text as memo_tex2_0_ 
    from
        tbl_memo memo0_ 
    order by
        memo0_.mno desc,
        memo0_.memo_text asc limit ?
Hibernate: 
    select
        count(memo0_.mno) as col_0_0_ 
    from
        tbl_memo memo0_
Page 1 of 10 containing com.example.entity.Memo instances

☆ 정렬결과

Memo(mno=100, memoText=Memo...100)
Memo(mno=99, memoText=Memo...99)
Memo(mno=98, memoText=Memo...98)
Memo(mno=97, memoText=Memo...97)
Memo(mno=96, memoText=Memo...96)
Memo(mno=95, memoText=Memo...95)
Memo(mno=94, memoText=Memo...94)
Memo(mno=93, memoText=Memo...93)
Memo(mno=92, memoText=Memo...92)
Memo(mno=91, memoText=Memo...91)
profile
비전공초보개발자

0개의 댓글