Book › DDD

Building Spring Data JPA read models with CQRS

Build Kotlin read models with Spring Data JPA specifications, projections, and Hibernate Subselect, and learn when to separate read and write storage.

Building Spring Data JPA read models with CQRS

An order write model can enforce cancellation rules and still be a poor fit for a list view. In these notes on Chapters 5 and 11 of Getting Started with Domain-Driven Development, I use Spring Data JPA specifications, DTO projections, and a Hibernate read mapping to separate the two concerns.

The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6.

Give writes and reads room to evolve separately

An Order aggregate owns rules that hold when you change an order. It can refer to a customer or product by ID and leave each object’s lifecycle alone. The order list has a different job. It may need the customer’s name, a representative product name, and the payment total in the same row.

Walking a collection of orders and loading related objects one by one can lead to N+1 queries. Switching to eager loading can move query cost into transactions that need only order state. Putting every screen filter and relationship on the domain model also makes an independently changing read requirement a reason to change the write model.

Command Query Responsibility Segregation (CQRS) gives writes and reads separate models. I keep changes behind the aggregate boundary and let the read side select the columns it actually needs.

flowchart TD
    Client["Client request"]
    Cmd["Command model (JPA aggregate)"]
    Qry["Read model (DAO / Subselect)"]
    WriteDB["Write store (RDB)"]
    ReadDB["Read store (same DB / search engine)"]

    Client -->|"Change state"| Cmd
    Client -->|"List or detail"| Qry
    Cmd --> WriteDB
    WriteDB -.->|"Sync if separated"| ReadDB
    Qry --> ReadDB
Read architectureImplementation costVisibility after writesUseful when
Separate models in one databaseReuses the database and its transactionsA query against the primary can see committed writesThe read complexity comes from joins or projections
Separate stores such as a replica or search indexNeeds a synchronization path such as replication, CDC, or messagingA read can lag behind the writeThe workload needs separate scaling, full-text search, or expensive aggregation

I start with a logically separate query model on the same database. A separate store is useful only once the workload justifies synchronization and its failure modes. A small CRUD workload can often use its existing repository without another set of models.

Compose filters with Spring Data Specifications

A search screen often needs optional filters. Specification<T> turns a domain condition into a criteria predicate. JpaSpecificationExecutor<T> runs those predicates through the repository. The Kotlin SpecBuilder in this example gives the calling code one place to skip absent inputs and combine the rest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// com/example/shop/order/query/SpecBuilder.kt
package com.example.shop.order.query

import org.springframework.data.jpa.domain.Specification

class SpecBuilder<T> {
    private val specs = mutableListOf<Specification<T>>()

    fun ifHasText(value: String?, supplier: (String) -> Specification<T>) {
        if (!value.isNullOrBlank()) specs.add(supplier(value))
    }

    fun <V : Any> ifNotNull(value: V?, supplier: (V) -> Specification<T>) {
        if (value != null) specs.add(supplier(value))
    }

    fun toSpec(): Specification<T> =
        specs.fold(Specification.where(null)) { acc, spec -> acc.and(spec) }
}

fun <T> specBuilder(block: SpecBuilder<T>.() -> Unit): Specification<T> =
    SpecBuilder<T>().apply(block).toSpec()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// com/example/shop/order/query/OrderSummarySpecs.kt
package com.example.shop.order.query

import com.example.shop.order.domain.OrderState
import org.springframework.data.jpa.domain.Specification
import java.time.LocalDateTime

object OrderSummarySpecs {
    fun ordererId(ordererId: String): Specification<OrderSummary> =
        Specification { root, _, cb -> cb.equal(root.get<String>("ordererId"), ordererId) }

    fun state(state: OrderState): Specification<OrderSummary> =
        Specification { root, _, cb -> cb.equal(root.get<OrderState>("state"), state) }

    fun orderDateBetween(from: LocalDateTime, to: LocalDateTime): Specification<OrderSummary> =
        Specification { root, _, cb -> cb.between(root.get("orderDate"), from, to) }
}

Internally, SimpleJpaRepository applies each specification through toPredicate() using the supplied Root, CriteriaQuery, and CriteriaBuilder. In Hibernate 6 the criteria model is translated through its Semantic Query Model before SQL execution and parameter binding. A string path such as root.get("ordererId") can break after a property rename. For more complex criteria, a generated JPA metamodel or Querydsl makes that dependency explicit at compile time. Spring Data JPA Specifications

Match the return type to the pagination contract

  • Page<T> exposes totals. Spring Data may execute a separate count query, so I reserve it for a screen that actually shows a count or the last page.
  • Slice<T> asks for one more row than the page size and can tell the caller whether another slice exists. That suits infinite scrolling without a total count.
  • List<T> returns the requested rows when the caller does not need page metadata.

A JPQL constructor expression projects selected values directly into a DTO. Here, OrderView has a constructor for the mapped value types and exposes strings and an integer to the caller. The DAO joins the order and member and returns a slice in a stable order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// com/example/shop/order/query/OrderView.kt
package com.example.shop.order.query

import com.example.shop.common.model.Money
import com.example.shop.member.domain.MemberId
import com.example.shop.order.domain.OrderNo
import com.example.shop.order.domain.OrderState

data class OrderView(
    val number: String,
    val state: OrderState,
    val memberName: String,
    val memberId: String,
    val totalAmounts: Int,
) {
    constructor(
        number: OrderNo,
        state: OrderState,
        memberName: String,
        memberId: MemberId,
        totalAmounts: Money,
    ) : this(number.number, state, memberName, memberId.id, totalAmounts.value)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// com/example/shop/order/query/OrderViewDao.kt
package com.example.shop.order.query

import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Slice
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.Repository
import org.springframework.data.repository.query.Param

interface OrderViewDao : Repository<OrderSummary, String> {
    @Query(
        """
        select new com.example.shop.order.query.OrderView(
            o.number, o.state, m.name, m.id, o.totalAmounts
        )
        from Order o
        join Member m on o.orderer.memberId = m.id
        where o.orderer.memberId.id = :ordererId
        order by o.number.number desc
        """
    )
    fun findByOrdererId(
        @Param("ordererId") ordererId: String,
        pageable: Pageable,
    ): Slice<OrderView>
}

A DTO projection does not create managed Hibernate entities or dirty-checking snapshots for the projected rows. JPQL names the DTO class in a string, so a package or constructor change can break the query even when the Kotlin code compiles. I exercise the repository query in an integration test.

Map a read-only query with Hibernate Subselect

For a reusable join that I want to query as an entity, Hibernate can map the result of a SQL subquery with @Subselect. This example maps an order summary without creating a physical database view.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// com/example/shop/order/query/OrderSummary.kt
package com.example.shop.order.query

import com.example.shop.order.domain.OrderState
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.Id
import org.hibernate.annotations.Immutable
import org.hibernate.annotations.Subselect
import org.hibernate.annotations.Synchronize
import java.time.LocalDateTime

@Entity
@Immutable
@Subselect(
    """
    select o.order_number as number, o.version as version,
           o.orderer_id as orderer_id, o.orderer_name as orderer_name,
           o.total_amounts as total_amounts, o.state as state,
           o.order_date as order_date, p.name as product_name
    from purchase_order o
    inner join order_line ol on o.order_number = ol.order_number
    inner join product p on ol.product_id = p.product_id
    where ol.line_idx = 0
    """
)
@Synchronize("purchase_order", "order_line", "product")
class OrderSummary(
    @Id @Column(name = "number") val number: String,
    @Column(name = "version") val version: Long,
    @Column(name = "orderer_id") val ordererId: String,
    @Column(name = "orderer_name") val ordererName: String,
    @Column(name = "total_amounts") val totalAmounts: Int,
    @Enumerated(EnumType.STRING) @Column(name = "state") val state: OrderState,
    @Column(name = "order_date") val orderDate: LocalDateTime,
    @Column(name = "product_name") val productName: String,
)

@Immutable makes updates to the mapped entity unnecessary and lets Hibernate omit its dirty-checking snapshot. @Synchronize lists the tables the SQL depends on so Hibernate can flush relevant changes before the query when auto-flush applies. With a shared stateful session, it still helps to avoid treating the mutable order and its read projection as two interchangeable managed representations. Hibernate Subselect documentation

Check the generated queries and freshness

Run EXPLAIN against the SQL Hibernate generates. An outer filter against a subselect may produce a different plan than the same filter in a direct query.

  • Check predicate pushdown and index use with representative filters and sort orders. GROUP BY, DISTINCT, and UNION can cause an optimizer to materialize a derived table.
  • Capture the SQL for the list endpoint. Confirm that the Slice path fetches one extra row without running an unnecessary count.
  • With separate stores, test what the user sees immediately after a successful command. Returning the essential summary in the command response, or reading that record from the primary, can bridge synchronization lag.
  • Revisit the split when it introduces new mapping code without solving a measurable query or ownership problem.
This post is licensed under CC BY 4.0 by the author.