Light Blue Pointer
본문 바로가기
Developing/TIL(Develop)

Spring에서 MongoDB 이용할때의 Pagination : MongoTemplate 으로 List<Model> , Page<Model> 리턴

by 개발바닥곰발바닥!!! 2024. 9. 22.
Pageable pageable = new PageRequests(page, size);
Query query = new Query().with(pageable);
List<XXX> list = mongoTemplate.find(query, XXX.class);
return PageableExecutionUtils.getPage(
                       list,
                       pageable,
                       () -> mongoTemplate.count(Query.of(query).limit(-1).skip(-1), XXX.class));

이렇게 하면 mongoTemplate이 Page를 지원하지 않는다고 해도 PageableExecutionUtils을 이용해서 Page에 담을 수 있다

List<Chat>으로 돌려보내는 방법

package kpring.chat.chat.repository

import kpring.chat.chat.model.Chat
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Repository

@Repository
class RoomChatCustomRepository(
  private val mongoTemplate: MongoTemplate,
) {
    fun findListByContextIdWithPaging(
    contextId: String,
    page: Int,
    size: Int,
  ): List<Chat> {
    val sort: Sort = Sort.by(Sort.Order.desc("createdAt"))
    val pageable: Pageable = PageRequest.of(page, size, sort)
    var query: Query = Query().with(pageable)
    return mongoTemplate.find(query, Chat::class.java)
  }
}

여기에다가 이 부분을 더하면 Page로 감싸서 돌려보낼 수 있다

return PageableExecutionUtils.getPage(
                       list,
                       pageable,
                       () -> mongoTemplate.count(Query.of(query).limit(-1).skip(-1), XXX.class));

나는 코틀린이라 이렇게 해 주었다

Page<Chat>으로 돌려보내는 방법

fun findPageByContextIdWithPaging(
    contextId: String,
    page: Int,
    size: Int,
  ): Page<Chat> {
    val sort: Sort = Sort.by(Sort.Order.desc("createdAt"))
    val pageable: Pageable = PageRequest.of(page, size, sort)
    val query: Query = Query().with(pageable)
    val list: List<Chat> = mongoTemplate.find(query, Chat::class.java)
    return PageableExecutionUtils.getPage(
      list,
      pageable,
      {
        mongoTemplate.count(Query.of(query).limit(-1).skip(-1), Chat::class.java)
      },
    )
  }

 

참고 자료 :

 

 

 

Pagination with mongoTemplate

I have a Query with Pageable: Query query = new Query().with(new PageRequests(page, size)) How can I execute it with MongoTemplate ? I don't see a single method returning Page<T>.

stackoverflow.com