Book › DDD

Designing DDD aggregates with references by ID

Use aggregate roots to protect order invariants in Kotlin, keep transactions focused, and weigh ID references against direct JPA associations.

Designing DDD aggregates with references by ID

An order total and its line items need to agree when a transaction commits. A customer’s profile can change independently. In these notes on Chapter 3 of Getting Started with Domain-Driven Development, I use that distinction to draw aggregate boundaries and decide where a reference by ID is enough.

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

Draw the boundary around a consistency rule

A large object graph shows that objects are related. An aggregate needs a stronger reason to exist. Its members share a lifecycle or a rule that has to be true when a change commits. If a product holds every review ever written about it, a simple review action can needlessly enlarge the product’s transaction and introduce lock contention.

An order is a different case. Its lines and total have to agree. The shipping address can change only before shipment. Those rules give Order, OrderLine, and ShippingInfo a common boundary. Member and Product have independent lifecycles, so the order can refer to them without owning them.

flowchart TD
    ROOT["Order (aggregate root)"] --> LINE["OrderLine (value collection)"]
    ROOT --> SHIP["ShippingInfo (internal value)"]
    ROOT -.->|"MemberId reference"| MEM["Member (external aggregate)"]
    LINE -.->|"ProductId reference"| PROD["Product (external aggregate)"]

When I find a candidate boundary, I list the invariants and ask what happens if two callers run in parallel. This makes it easier to spot a separate object that only happens to share a screen. It also exposes a rule that spans two objects and would otherwise be enforced in whichever service happened to load them.

Route every change through the root

Order is the aggregate root. If an application service can append directly to a mutable order-line list, it can skip recalculation and validation. The root keeps its mutable list private, exposes a copy, and changes its state through behavior methods. The nested values in this example are immutable, so copying the list is enough to prevent callers from mutating them through the returned collection.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// com/example/shop/order/domain/Order.kt
package com.example.shop.order.domain

import com.example.shop.common.model.Money
import jakarta.persistence.CollectionTable
import jakarta.persistence.Column
import jakarta.persistence.ElementCollection
import jakarta.persistence.Embedded
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.JoinColumn
import jakarta.persistence.OrderColumn
import jakarta.persistence.Table

@Entity
@Table(name = "purchase_order")
class Order(
    @EmbeddedId
    val number: OrderNo,
    @Embedded
    val orderer: Orderer,
    orderLines: List<OrderLine>,
    shippingInfo: ShippingInfo
) {
    @ElementCollection
    @CollectionTable(name = "order_line", joinColumns = [JoinColumn(name = "order_number")])
    @OrderColumn(name = "line_idx")
    private val _orderLines: MutableList<OrderLine> = mutableListOf()

    val orderLines: List<OrderLine>
        get() = _orderLines.toList()

    @Column(name = "total_amounts")
    var totalAmounts: Money = Money(0)
        protected set

    @Embedded
    var shippingInfo: ShippingInfo = shippingInfo
        protected set

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    var state: OrderState = OrderState.PAYMENT_WAITING
        protected set

    init {
        replaceOrderLines(orderLines)
    }

    fun changeShippingInfo(newShippingInfo: ShippingInfo) {
        verifyNotYetShipped()
        this.shippingInfo = newShippingInfo
    }

    fun cancel() {
        verifyNotYetShipped()
        this.state = OrderState.CANCELED
    }

    fun verifyNotYetShipped() {
        check(state == OrderState.PAYMENT_WAITING || state == OrderState.PREPARING) {
            "Cannot change or cancel the order in its current state: $state"
        }
    }

    private fun replaceOrderLines(lines: List<OrderLine>) {
        require(lines.isNotEmpty()) { "An order requires at least one line." }
        _orderLines.clear()
        _orderLines.addAll(lines)
        this.totalAmounts = Money(lines.sumOf { it.amounts.value })
    }
}

I ordinarily change one aggregate per transaction. Within Spring’s @Transactional boundary, Hibernate flush processing detects dirty entities and queues SQL, while the database controls locking. Updating more aggregates can touch more rows and hold more locks until commit. On InnoDB, updates take exclusive record locks, which creates room for lock waits and deadlocks if another transaction takes those locks in a different order.

A domain event lets another aggregate catch up after the first change commits when the business rule allows eventual consistency. If a use case truly needs two aggregates to commit together, I make the coordination explicit in the application service. That keeps the decision visible and avoids teaching one root to reach into another root’s repository.

Prefer roots for repositories and IDs for references

I expose a repository for Order. Adding an OrderLineRepository for writes would create a path around the order’s rules. The order stores a MemberId and the lines store ProductId values. These types express which external entity each value identifies without creating a path to change it implicitly.

ConcernJPA object association such as @ManyToOneValue reference such as MemberId
Aggregate accessThe object graph makes another root reachableThe application explicitly loads the root it needs
LoadingDepends on fetch strategy and proxy initializationEach lookup is visible in the use case
StorageThe mapping often assumes one databaseThe identity can survive a move to separate databases
ReadsNavigation is directCombining data needs a dedicated query or read model
1
2
3
4
5
6
7
8
9
10
11
12
// com/example/shop/member/domain/MemberId.kt
package com.example.shop.member.domain

import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import java.io.Serializable

@Embeddable
data class MemberId(
    @Column(name = "member_id")
    val id: String
) : Serializable
1
2
3
4
5
6
7
8
9
10
11
12
// com/example/shop/catalog/domain/ProductId.kt
package com.example.shop.catalog.domain

import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import java.io.Serializable

@Embeddable
data class ProductId(
    @Column(name = "product_id")
    val id: String
) : Serializable
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
// com/example/shop/order/domain/OrdererAndLine.kt
package com.example.shop.order.domain

import com.example.shop.catalog.domain.ProductId
import com.example.shop.common.model.Money
import com.example.shop.member.domain.MemberId
import jakarta.persistence.AttributeOverride
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.Embedded

@Embeddable
data class Orderer(
    @Embedded
    @AttributeOverride(name = "id", column = Column(name = "orderer_id"))
    val memberId: MemberId,
    @Column(name = "orderer_name")
    val name: String
)

@Embeddable
data class OrderLine(
    @Embedded
    val productId: ProductId,
    @Column(name = "price")
    val price: Money,
    @Column(name = "quantity")
    val quantity: Int,
    @Column(name = "amounts")
    val amounts: Money = price * quantity
)

A direct association can be useful where navigating the relationship is part of the model and both objects share its persistence boundary. Across aggregates, I prefer to make the load explicit so the use case shows whether it depends on orders, products, or both.

Keep read paths and large collections predictable

An ID reference trades automatic navigation for explicit access. A list query that fetches 20 orders and then calls ProductRepository.findById() once per row can issue 21 queries. That is still an N+1 pattern. For a view that combines aggregates, I use a DTO projection or joined query such as the Spring Data JPA read models example. The write path keeps its invariant boundaries and the read path fetches the fields the screen needs.

I avoid loading high-cardinality relationships in the direction that produces the largest collection. A product can hold CategoryId and be looked up by category. A many-to-many relationship can keep a set of category IDs on the side that owns the association, provided that set stays bounded.

If the state of one aggregate determines whether another can be created, a factory method can keep the creation rule close to the state it checks. Store.createProduct() prevents registrations from a blocked store. The application still loads and saves the relevant roots.

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

import com.example.shop.common.model.Money

class Store(
    val id: String,
    var blocked: Boolean = false
) {
    fun createProduct(newProductId: ProductId, name: String, price: Money): Product {
        check(!blocked) { "A blocked store cannot register products. storeId=$id" }
        return Product(id = newProductId, storeId = id, name = name, price = price)
    }
}

class Product(
    val id: ProductId,
    val storeId: String,
    val name: String,
    val price: Money
)

Check invariants, queries, and referential integrity

An ID reference in the object model does not dictate the database’s foreign keys. In one database, a foreign key protects a reference even when application code makes a mistake. Parent-row checks can add lock contention, and separate databases change the enforcement options.

  • Test that every public change leaves the order total consistent with its lines.
  • Record the SQL for list views and check whether a row loop triggers unexpected lookups.
  • When two roots must commit together, document why the rule cannot tolerate delayed updates.
  • Before removing a foreign key, decide how invalid references will be prevented or detected and repaired.
This post is licensed under CC BY 4.0 by the author.