skip to content

In Spring Data, what are CoroutineCrudRepository and CoroutineSortingRepository, and why can't a Kotlin team on Spring Data JPA simply switch to them?

level: middleimportance: should knowfreq 38%

answer

  1. Kotlin face of reactive repositories
  2. suspend for one, Flow for many
  3. needs a reactive store module
  4. core, reactive and reactor artifacts

basics

~10 s

CoroutineCrudRepository and CoroutineSortingRepository are Spring Data's Kotlin repository interfaces: suspend functions for single results, Flow for many. They sit on the reactive repository infrastructure, so blocking JPA cannot back them.

solid answer

~50 s

`CoroutineCrudRepository<T, ID>` is the coroutine counterpart of the CRUD interface: `save`, `findById`, `count` and the deletes are `suspend` functions, while `findAll`, `findAllById` and `saveAll` return `Flow`. `CoroutineSortingRepository` adds only `findAll(sort: Sort): Flow<T>` and is meant to be combined with the CRUD one. Query methods you declare follow the same rule: `suspend` for one value (or a `List`), `Flow` for a stream. Under the hood they are built on the **reactive** repository infrastructure: the store's base implementation returns `Mono`/`Flux` and Spring Data bridges that to coroutines, which is why `kotlinx-coroutines-reactive` and `kotlinx-coroutines-reactor` must be on the classpath. JPA has no reactive repository support, so with those libraries present a JPA app rejects the interface at startup. The JPA options are to keep a blocking repository and call it on `Dispatchers.IO`, or move to a reactive store such as R2DBC.

code

kotlin · 17 lines
kotlin
import kotlinx.coroutines.flow.Flow
import org.springframework.data.annotation.Id
import org.springframework.data.repository.kotlin.CoroutineCrudRepository
import org.springframework.data.repository.kotlin.CoroutineSortingRepository

data class Customer(@Id val id: Long?, val lastName: String, val city: String)

interface CustomerRepository :
    CoroutineCrudRepository<Customer, Long>,
    CoroutineSortingRepository<Customer, Long> {

    suspend fun findFirstByLastName(lastName: String): Customer?

    fun findByCity(city: String): Flow<Customer>

    suspend fun findAllByLastName(lastName: String): List<Customer>
}

go deeper

for a junior

Recall the two interface names and the shape rule: suspend functions return one value or nothing, Flow returns a stream. Know that findById gives a nullable entity, not an Optional.

for a middle

Explain that these interfaces sit on the reactive repository infrastructure, which is why they need Reactor plus the kotlinx-coroutines reactive and reactor bridges, and why a blocking store like JPA cannot back them.

for a senior

Spot the JPA migration mistake before it ships: the interface swap fails at startup, and the honest fix is a blocking repository on Dispatchers.IO or a deliberate move of that aggregate to a reactive store.

for a principal

Frame the choice as a persistence-model decision, not an API style: coroutine repositories pay off only on a fully non-blocking path, and adopting them means giving up JPA's persistence context for that data.

## What the coroutine repository interfaces are Spring Data Commons ships two Kotlin interfaces in the package `org.springframework.data.repository.kotlin`, both available since Spring Data Commons 2.3: - **`CoroutineCrudRepository<T, ID>`** extends the `Repository<T, ID>` marker and is annotated `@NoRepositoryBean`, exactly like the blocking CRUD interface. It declares the CRUD vocabulary in coroutine form. - **`CoroutineSortingRepository<T, ID>`** also extends `Repository<T, ID>` and declares a single method, `findAll(sort: Sort): Flow<T>`. Its own documentation says it should usually be combined with `CoroutineCrudRepository`, and the reference docs note that coroutine repositories are discovered when the interface extends `CoroutineCrudRepository`. There is no coroutine paging interface in that package: sorting is offered, `Pageable`-based paging is not. A **coroutine** is a suspendable computation: a `suspend` function can pause without holding a thread and resume when its data arrives. A **`Flow<T>`** (from kotlinx.coroutines) is a cold, asynchronous stream of values that starts producing only when someone calls `collect`. ## The method shapes The rule is the same as the reactive-to-coroutines translation in the reference docs: a `Mono<T>` becomes a `suspend` function returning `T` or `T?`, a `Mono<Void>` becomes a `suspend` function returning nothing, and a `Flux<T>` becomes a function returning `Flow<T>`. | Operation | Signature on `CoroutineCrudRepository` | |---|---| | save one | `suspend fun <S : T> save(entity: S): T` | | save many | `fun <S : T> saveAll(entities: Iterable<S>): Flow<S>` (also a `Flow<S>` overload) | | find one | `suspend fun findById(id: ID): T?` | | find many | `fun findAll(): Flow<T>`, `fun findAllById(ids: Iterable<ID>): Flow<T>` | | aggregate | `suspend fun count(): Long`, `suspend fun existsById(id: ID): Boolean` | | delete | `suspend fun deleteById(id: ID)`, `suspend fun delete(entity: T)`, `suspend fun deleteAll()` | A missing row from `findById` is a Kotlin `null`, not an `Optional`, so the type system forces the caller to handle absence. Query methods you declare follow the same shapes: 1. `suspend fun findOne(id: String): User` retrieves one value by suspending. 2. `fun findByFirstname(name: String): Flow<User>` returns a stream; the `Flow` is created at once but the query runs when it is collected. 3. `suspend fun findAllByFirstname(name: String): List<User>` suspends and returns the whole result as a list; Spring Data collects the underlying stream into the list for you. 4. A plain `fun getUser(): User` (neither `suspend` nor `Flow`) **blocks the calling thread** and loses the coroutine context; the reference docs say to avoid it. ## Why they are built on reactive repositories The coroutine interfaces are not a separate data-access stack. The reference docs state that coroutine repositories are built on reactive repositories. At runtime: - The store module supplies a **reactive base implementation** whose methods return Reactor `Mono` and `Flux`. - When you call a `suspend` method, Spring Data strips the hidden `Continuation` parameter the Kotlin compiler adds, invokes the reactive implementation, and adapts the result: a `Mono` is awaited, a `Flux` is reduced to a single value, or collected into a list when the declared return type is a collection. - A method declared to return `Flow` gets the reactive stream converted to a `Flow`. That adaptation runs through Spring's reactive adapter registry, which registers `Flow` as a multi-value reactive type **only when Reactor and kotlinx-coroutines-reactor are both present**. That is why the docs list three dependencies: `kotlinx-coroutines-core`, `kotlinx-coroutines-reactive` and `kotlinx-coroutines-reactor`. Spring Boot manages their versions through the kotlinx-coroutines BOM, so you add them without version numbers. So only store modules that provide reactive repositories can back a coroutine repository, for example Spring Data R2DBC and Spring Data MongoDB's reactive support. ## The JPA scenario A Kotlin team on Spring Data JPA changes `interface OrderRepository : CrudRepository<Order, Long>` to extend `CoroutineCrudRepository` instead, hoping for non-blocking persistence. What happens depends on the classpath: - **With Reactor and kotlinx-coroutines-reactor present**, Spring Data sees `Flow` in the interface's method signatures and classifies it as a reactive repository. The default configuration in Spring Data Commons rejects reactive repositories unless the store module overrides that check, and JPA has no reactive repositories, so startup fails with `InvalidDataAccessApiUsageException`: "Reactive Repositories are not supported by …". - **Without kotlinx-coroutines-reactor**, `Flow` is not recognised as a reactive type at all, so nothing can bridge the coroutine methods to an implementation. The interface does not become a working coroutine repository either; it just fails less clearly. The deeper reason is that JPA and JDBC are blocking APIs: an `EntityManager` call holds its thread until the database answers. Changing the interface does not change the driver underneath. The realistic choices are: - Keep a blocking repository and call it from coroutines inside `withContext(Dispatchers.IO)`, which moves the blocking call off the caller's thread without pretending it is non-blocking. - Move the aggregate to a store with reactive repositories, such as R2DBC, accepting that this is a different persistence model (no persistence context, lazy loading or dirty checking). ## Choosing between the two coroutine interfaces - Extend `CoroutineCrudRepository` when the repository needs the CRUD surface. - Add `CoroutineSortingRepository` beside it when callers need `findAll(Sort)`. - For a deliberately narrow API, extend only the CRUD one and declare the few query methods you want, keeping the smallest-surface principle the blocking hierarchy follows.

  • Can a coroutine repository query method declare suspend and return a List instead of a Flow?
    Yes. When a suspend method's declared return type is a collection, Spring Data collects the reactive store's result stream into a list before resuming the caller. The query still runs non-blocking; you only give up incremental processing, since the whole result is held in memory at once. Use `Flow` when the result can be large or should be processed as it arrives.
  • What is wrong with declaring a plain non-suspend method returning an entity on a coroutine repository?
    A method that is neither `suspend` nor returns `Flow` has to produce its value synchronously, so it blocks the calling thread while the reactive query completes, and it loses the coroutine context. The Spring Data reference docs call this out as something to avoid. Declare it `suspend` for one value or return `Flow` for many.
  • If a JPA team really needs non-blocking access, what does moving to R2DBC cost them?
    R2DBC repositories support coroutine interfaces, but the persistence model changes: there is no persistence context, no lazy-loaded associations and no dirty checking, so saves are explicit and relationships are loaded by hand. It is a data-access redesign for that aggregate, not an interface swap, and the gain only appears if the rest of the request path is non-blocking too.

A travel plug adapter: it turns one socket shape into another, but it needs a live socket behind it. CoroutineCrudRepository adapts a reactive repository into suspend and Flow calls; on a blocking store like JPA there is no reactive socket to adapt.

  • Extending CoroutineCrudRepository makes Spring Data JPA queries non-blocking.
  • Spring Data JPA runs coroutine repository methods on Dispatchers.IO automatically.
  • kotlinx-coroutines-core alone is enough because Flow lives there.
  • CoroutineCrudRepository.findAll() suspends and returns a List of every entity.
  • A plain non-suspend method returning an entity is still non-blocking on a coroutine repository.
  • Coroutine repositories are a separate stack, unrelated to Spring Data's reactive repositories.