Pagination for CoroutineCrudRepository



我在Spring Boot项目中使用kotlin协程,我使用Spring Data访问MongoDB。

一切工作正常,例如findAll(),但当我使用分页时,Spring在启动时抛出异常

IllegalStateException: Method has to use a either 
multi-item reactive wrapper return type or a wrapped Page/Slice type.
我的代码如下:
@Repository
interface CoroutinesActivityRepository : CoroutineCrudRepository<Activity, String> {
suspend fun findAllOrderByTitle(page: Pageable): Flow<Activity>
}
data class Activity(val id: String? = null, val title: String)

CoroutineCrudRepository是否可以应用分页?对我来说唯一有效的方法是使用ReactiveMongoTemplate

@Component
class CoroutinesActivityRepository(
private val mongoTemplate: ReactiveMongoTemplate
) {
suspend fun findAllOrderByTitle(page: Pageable): Flow<Activity> =
mongoTemplate.find(Query().with(page), Activity::class.java).asFlow()
}

我知道已经很晚了,但是为了将来的参考…

尝试相同,但删除suspend:

fun findAllOrderByTitle(page: Pageable): Flow<Activity>

如果这解决了错误,但分页不能正常工作,您总是可以使用@Query。同样,不要使用suspend

要使用@Query手动实现分页,可以使用LIMITOFFSET。例如:

@Query("""
select * from table limit :size offset :offset
""")
fun findAll(offset: Int, size: Int): Flow<DataClass>

pagesize变量中计算offset:

val offset = size * (page - 1)

我希望这对你有帮助!

使用

@GetMapping("/student")
suspend fun getStudents(
@RequestParam offset: Int,
@RequestParam limit: Int
) =
ListResponse.success(
studentRepository
.findAll()
.drop(offset)
.take(limit).toList()
)

相关内容

  • 没有找到相关文章

最新更新