Mapping DDD aggregates with Spring Data JPA
Map Kotlin aggregate roots with Spring Data JPA, choose value and collection mappings, and control lifecycle, fetching, and proxy configuration.
Spring Data JPA can persist an order aggregate while giving its callers a narrow API. These notes on Chapter 4 of Getting Started with Domain-Driven Development cover the repository interface, value mappings, and Kotlin settings behind that boundary.
The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6.
Expose the operations the aggregate needs
I put OrderRepository alongside the order model. The interface declares the operations the use cases need. Extending the Spring Data marker Repository keeps infrastructure methods such as flush() and deleteAllInBatch() out of the domain-facing API. The interface still has a Spring Data dependency. A domain module that must avoid that dependency can declare its own interface and let an adapter wrap a Spring Data repository.
1
2
3
4
5
6
7
8
9
10
// com/example/shop/order/domain/OrderRepository.kt
package com.example.shop.order.domain
import org.springframework.data.repository.Repository
interface OrderRepository : Repository<Order, OrderNo> {
fun findById(id: OrderNo): Order?
fun save(order: Order): Order
fun delete(order: Order)
}
At startup, Spring Data JPA registers repository factory beans. JpaRepositoryFactoryBean supplies a proxy that routes the repository method to a query implementation or a base implementation such as SimpleJpaRepository. This base implementation uses an EntityManager for persistence operations. A service can call the repository without choosing how to manage the persistence context.
flowchart TD
APP["Application (OrderService)"] --> REPO["OrderRepository (domain interface)"]
REPO --> FACTORY["JpaRepositoryFactoryBean (proxy factory)"]
FACTORY --> SIMPLE["SimpleJpaRepository (infrastructure implementation)"]
SIMPLE --> DB["EntityManager / RDBMS"]
Map each value according to the columns it owns
OrderNo represents an order identifier and gives signatures more meaning than a plain String. In this mapping it uses @EmbeddedId. Jakarta Persistence 3.1 requires a primary key class to be serializable and to implement equality and hashing consistent with database equality. An immutable Kotlin data class offers those value semantics when its fields represent the key columns directly. Jakarta Persistence 3.1
Composite values such as Orderer, ShippingInfo, and OrderLine use @Embeddable. If two embedded fields would otherwise produce the same column names, @AttributeOverride can give each occurrence its own column. A value that maps to one primitive column, such as Money, can use an AttributeConverter. With autoApply = true, the example converter consistently maps eligible Money attributes to integer columns.
1
2
3
4
5
6
7
8
9
10
11
// com/example/shop/common/model/MoneyConverter.kt
package com.example.shop.common.model
import jakarta.persistence.AttributeConverter
import jakarta.persistence.Converter
@Converter(autoApply = true)
class MoneyConverter : AttributeConverter<Money, Int> {
override fun convertToDatabaseColumn(attribute: Money?): Int? = attribute?.value
override fun convertToEntityAttribute(dbData: Int?): Money? = dbData?.let { Money(it) }
}
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// com/example/shop/order/domain/OrderMapping.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.CollectionTable
import jakarta.persistence.Column
import jakarta.persistence.ElementCollection
import jakarta.persistence.Embeddable
import jakarta.persistence.Embedded
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.FetchType
import jakarta.persistence.JoinColumn
import jakarta.persistence.OrderColumn
import jakarta.persistence.Table
import java.io.Serializable
@Embeddable
data class OrderNo(
@Column(name = "order_number")
val number: String
) : Serializable
@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
)
@Entity
@Table(name = "purchase_order")
class Order(
@EmbeddedId
val number: OrderNo,
@Embedded
val orderer: Orderer,
orderLines: List<OrderLine>,
shippingInfo: ShippingInfo
) {
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "order_line", joinColumns = [JoinColumn(name = "order_number")])
@OrderColumn(name = "line_idx")
private val _orderLines: MutableList<OrderLine> = orderLines.toMutableList()
val orderLines: List<OrderLine>
get() = _orderLines.toList()
@Column(name = "total_amounts")
var totalAmounts: Money = Money(orderLines.sumOf { it.amounts.value })
protected set
@Embedded
var shippingInfo: ShippingInfo = shippingInfo
protected set
@Enumerated(EnumType.STRING)
@Column(name = "state")
var state: OrderState = OrderState.PAYMENT_WAITING
protected set
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"
}
}
}
Choose a collection mapping by how rows change
| Mapping | Storage | SQL to watch for | Useful when |
|---|---|---|---|
@ElementCollection with @CollectionTable | Child rows such as order_line | Hibernate may delete and reinsert rows when it cannot target individual values | The collection is small and its values need SQL queries |
| Converter to a single column | Delimited or JSON value on the parent row | A parent-row update replaces the serialized value | The values are read and written as a unit |
Separate entities with @OneToMany | Child rows with their own primary keys | Independently identified rows can be updated individually | Collections are large, frequently edited, or need their own history |
Values in an element collection have no independent persistent identity. Depending on the collection shape and mapping, Hibernate may delete and recreate rows for that owner. @OrderColumn preserves order and can require renumbering rows after a middle element is removed. I inspect generated SQL for the real edit pattern before deciding whether those rows need separate identities.
Control fetching, cascading, and identifiers
Load attributes lazily where practical and request joins or an @EntityGraph for a specific use case. That makes a list or scalar status check cheaper when it does not need the full aggregate. The fetch plan is worth testing. An eager association can cause secondary fetches, and paginating a collection fetch join can cause Hibernate’s HHH90003004 warning and in-memory pagination. The query models discussion has an option for a view that spans several aggregates.
Embedded values and element collections already belong to the lifetime of their owner. Cascade settings matter when child objects are entities. Use CascadeType.ALL and orphanRemoval = true when those children really share the root’s lifetime. Order rows may still be needed for audit or settlement, so this example models cancellation as a state transition. A soft deletion timestamp is another option where the business treats a row as inactive.
Identifier generation is also a persistence decision. Users can supply some IDs, and a domain rule can generate OrderNo before saving. With a database IDENTITY generator, Hibernate generally needs an insert to obtain the ID, and it cannot batch those identity inserts in the usual JDBC way. An assigned domain ID is already available when code records an event or exercises the model in a unit test.
Configure Kotlin for JPA and verify at runtime
Kotlin classes are final by default, and a provider needs a no-arg construction path for these JPA mappings. For the Kotlin version in this example, the JPA compiler preset supplies the synthetic constructor, while the all-open configuration allows the provider to subclass eligible types for proxies.
1
2
3
4
5
6
7
8
9
10
11
12
// build.gradle.kts
plugins {
kotlin("jvm") version "1.9.25"
kotlin("plugin.spring") version "1.9.25"
kotlin("plugin.jpa") version "1.9.25"
}
allOpen {
annotation("jakarta.persistence.Entity")
annotation("jakarta.persistence.MappedSuperclass")
annotation("jakarta.persistence.Embeddable")
}
If a target entity stays final, the provider may have to load it when it would otherwise create a proxy. I verify the fetch behavior with SQL rather than relying on the annotation alone. I also choose field or property access consistently. In this model, the annotations map fields and mutations go through behavior methods or restricted setters.
The no-arg compiler plugin does not run initialization logic in the generated constructor by default. Keep restoration from the database separate from invariants enforced while creating a new aggregate. Kotlin no-arg compiler plugin
Checks before accepting the mapping
- Save and reload an order to confirm the embedded identifier and nested column mappings.
- Inspect SQL for a collection update, a paged list, and a fetch of one full aggregate.
- Confirm that proxies and field access work with the application’s compiler settings.
- Keep repository methods at the aggregate root boundary, including when evolving deletion rules.
