개발/Spring

[JPA] Page, nativeQuery사용

Ridiss 2021. 7. 13. 15:00

Controller

    @GetMapping("/api/image")
    public ResponseEntity<?> imageStory(@AuthenticationPrincipal PrincipalDetails principalDetails,
                                        @PageableDefault(size = 3) Pageable pageable) {
        Page<Image> images = imageService.이미지스토리(principalDetails.getUser().getId(), pageable);
        return new ResponseEntity<>(new CMRespDto<>(1, "성공", images), HttpStatus.OK);
    }

@PageableDefault(size = 3) Pageable pageable 추가 후 

리턴받는 타입을 Page로 설정한다.

 

import는

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

 

Service

    @Transactional(readOnly = true) 
    public Page<Image> 이미지스토리(int principalId, Pageable pageable){
        Page<Image> images = imageRepository.mStory(principalId, pageable);
        return images;
    }

 

Repository

    @Query(value = "SELECT A.* FROM image A\n" +
            "INNER JOIN subscribe B\n" +
            "ON A.userId = B.toUserId\n" +
            "WHERE B.fromUserId = :principalId ORDER BY A.id DESC"
            , countQuery = "SELECT COUNT(*) FROM image A\n" +
            "INNER JOIN subscribe B\n" +
            "ON A.userId = B.toUserId\n" +
            "WHERE B.fromUserId = :principalId"
            , nativeQuery = true)
    Page<Image> mStory(int principalId, Pageable pageable);

 

 

 

'개발 > Spring' 카테고리의 다른 글

Spring Security 6 변경점  (0) 2023.01.25
SPRING-Security SessionManagement(세션 관리 기능)  (0) 2023.01.23
Spring-IOC  (0) 2022.03.01
@Component, @Configuration 차이  (0) 2021.08.04
JPA 양방향 매핑시 주의점  (0) 2021.05.24