Search

61. 스프링부트 포토그램 스토리페이지 페이징하기

스토리 페이지

3. 페이징 처리하기

지금 뿌려주는걸 3개씩 뿌려주게 페이징 처리를 할거다.
ImageApiController.java
@PageableDefault(size=3, sort="id", direction =Sort.Direction.DESC) Pageable pageable
JavaScript
복사
@GetMapping("/api/image") public ResponseEntity<?> imageStory(@AuthenticationPrincipal PrincipalDetails principalDetails, @PageableDefault(size=3, sort="id", direction =Sort.Direction.DESC) Pageable pageable){ List<Image> images = imageService.이미지스토리(principalDetails.getUser().getId()); return new ResponseEntity<>(new CMRespDto<>(1, "성공", images), HttpStatus.OK); }
JavaScript
복사
.domain인 애로 import 해야한다
그리고 이미지스토리 함수에 pageable도 추가해서 던져준다.
@GetMapping("/api/image") public ResponseEntity<?> imageStory(@AuthenticationPrincipal PrincipalDetails principalDetails, @PageableDefault(size=3, sort="id", direction =Sort.Direction.DESC) Pageable pageable){ List<Image> images = imageService.이미지스토리(principalDetails.getUser().getId(),pageable); return new ResponseEntity<>(new CMRespDto<>(1, "성공", images), HttpStatus.OK); }
JavaScript
복사
ImageService.java
pageable받아서 mStory에도 던져준다
@Transactional(readOnly = true) // 영속성 컨텍스트 변경 감지를 해서, 더티체킹, flush(반영) X public List<Image> 이미지스토리(int principalId, Pageable pageable) { List<Image> images = imageRepository.mStory(principalId, pageable); return images; }
JavaScript
복사
ImageRepository.java
@Query(value = "SELECT * FROM image WHERE userId IN (SELECT toUserId FROM Subscribe WHERE fromUserId = :principalId)", nativeQuery = true) List<Image> mStory(int principalId, Pageable pageable);
JavaScript
복사
스토리를 가져올때 3건씩 최신순으로 정렬해서 갖고온다.
3건씩 갖고온다.

*네이티브 쿼리 외

컨트롤러 단에서 네이티브 쿼리로
@PageableDefault(size=3, sort="id", direction =Sort.Direction.DESC)
JavaScript
복사
써도 되고
@PageableDefault(size=3)
JavaScript
복사
이렇게만 쓰고
public interface ImageRepository extends JpaRepository<Image, Integer>{ @Query(value = "SELECT * FROM image WHERE userId IN (SELECT toUserId FROM Subscribe WHERE fromUserId = :principalId) ORDER BY id DESC", nativeQuery = true) Page<Image> mStory(int principalId, Pageable pageable); }
JavaScript
복사
이렇게 써도 된다. (List 부분을 다 Page로 변경해서 진행)
그러면 밑에 방식으로도 되는지 진행해보면은
오류난다…
첫번째 줄 오류는 프로필사진 관련오류라서 지금은 신경안써도 된다
포스트맨에서
주소 뒤에 ?page=0 이렇게 해서 1페이지 2페이지에 갖고오는 데이터를 미리 볼 수 있다.
{ "code": 1, "message": "성공", "data": { "content": [ { "id": 10, "caption": "포차코3", "postImageUrl": "c8e79fcf-ac6e-4553-8a1b-ad71e37c2c5a_포차코3.jpeg", "user": { "id": 3, "username": "love", "password": "$2a$10$jg0DHDzk.LkVGZdcaJ26uO8aFa/QbSBd5tfF9/iWP8sMgEVHa2G6S", "name": "러브", "website": null, "bio": null, "email": "love@nate.com", "phone": null, "gender": null, "profileImageUrl": null, "role": "ROLE_USER", "createDate": "2023-09-09T22:10:06.007228" }, "createDate": "2023-10-02T15:27:04.049478" }, { "id": 9, "caption": "포차코2", "postImageUrl": "06acf7d2-e24e-43fe-b964-6728f52dbebe_포차코2.jpeg", "user": { "id": 3, "username": "love", "password": "$2a$10$jg0DHDzk.LkVGZdcaJ26uO8aFa/QbSBd5tfF9/iWP8sMgEVHa2G6S", "name": "러브", "website": null, "bio": null, "email": "love@nate.com", "phone": null, "gender": null, "profileImageUrl": null, "role": "ROLE_USER", "createDate": "2023-09-09T22:10:06.007228" }, "createDate": "2023-10-02T15:26:55.388731" }, { "id": 8, "caption": "포차코1", "postImageUrl": "cfbb2a77-7d8e-448c-9533-da80ea69931c_포차코1.jpeg", "user": { "id": 3, "username": "love", "password": "$2a$10$jg0DHDzk.LkVGZdcaJ26uO8aFa/QbSBd5tfF9/iWP8sMgEVHa2G6S", "name": "러브", "website": null, "bio": null, "email": "love@nate.com", "phone": null, "gender": null, "profileImageUrl": null, "role": "ROLE_USER", "createDate": "2023-09-09T22:10:06.007228" }, "createDate": "2023-10-02T15:26:48.600959" } ], "pageable": { "sort": { "unsorted": true, "sorted": false, "empty": true }, "pageSize": 3, "pageNumber": 0, "offset": 0, "paged": true, "unpaged": false }, "totalPages": 3, "totalElements": 8, "last": false, "numberOfElements": 3, "number": 0, "sort": { "unsorted": true, "sorted": false, "empty": true }, "first": true, "size": 3, "empty": false } }
JSON
복사
json 형태로보면 content안에 담아서 오는걸 확인
story.js에 content 추가
// (1) 스토리 로드하기 function storyLoad() { $.ajax({ url:`/api/image`, dataType: "json" }).done(res=>{ console.log(res); res.data.content.forEach((image)=>{ let storyItem = getStoryItem(image); $("#storyList").append(storyItem); }); }).fail(error=>{ console.log("오류", error) }); }
JavaScript
복사
주소창에
http://localhost:8080/api/image?page=2
치면은
이런식으로 볼 수 있다.

*참고