---
title: "Transactional Outbox with Spring Modulith (JPA)"
description: "ZenWave example of a DDD aggregate (Customer, Address, PaymentMethods) with JPA, REST and AsyncAPI, publishing Avro domain events to Kafka through a transactional outbox with Spring Modulith events."
url: https://www.zenwave360.io/docs/examples/ddd-examples/transactional-outbox-modulith-jpa/
---

# Transactional Outbox with Spring Modulith (JPA)

A DDD Aggregate with JPA persistence, a REST API, and Domain Events published to Kafka through a Transactional Outbox with Spring Modulith Events.

This is a ZenWave designed and generated project around a `Customer` aggregate (with `Address` and `PaymentMethod` entities) persisted with JPA, exposed as a REST API defined with OpenAPI, and publishing Domain Events defined with AsyncAPI. Events are Avro records sent to Kafka with Spring Cloud Stream. They are stored in the Spring Modulith Event Publication Registry in the same database transaction as the aggregate, so the outbox comes from Spring Modulith and the externalization to Spring Cloud Stream comes from [`io.zenwave360.sdk:spring-modulith-events-scs`](https://github.com/ZenWave360/spring-modulith-events-spring-cloud-stream).

The project is also the reference application and integration test bed for `spring-modulith-events-scs`. You can find the [Complete Source Code](https://github.com/ZenWave360/zenwave-playground/tree/v20261205/examples/transactional-outbox-modulith-jpa) at GitHub (tag `v20261205`). For the background on the pattern, read [Transactional OutBox With AsyncAPI, Spring Cloud Stream and Spring Modulith](https://www.zenwave360.io/posts/TransactionalOutBoxWithAsyncAPIAndSpringModulith/).

## What You'll Learn

- How to model a DDD aggregate using ZDL
- Generate REST APIs from domain models
- Implement event-driven architecture with AsyncAPI
- Publish Domain Events through a Transactional Outbox with Spring Modulith Events and Spring Cloud Stream
- Create a complete Spring Boot microservice

We assume you have already read the [Getting Started](https://www.zenwave360.io/docs/getting-started.md) section and installed ZenWave SDK CLI and IntelliJ Plugin and are somewhat familiar with the concepts of DDD and Event-Driven Architecture.

## What we will be building: A Customer Master Data Service

We will be building a Java/SpringBoot microservice exposing CRUD operations for a `Customer` aggregate as a REST API and publishing Domain Events to Kafka through a Transactional Outbox.

The `Customer` entity is the root of the aggregate, holding relationships to other entities:

- an array of `Address` entities stored in a JSON column in the database and
- a `@OneToMany` collection of `PaymentMethod` entities.

NOTE: In this example, the `Customer` aggregate represents a cluster of related entities that are persisted and managed as a single unit. However, the business logic resides in the `CustomerService` class rather than within the entities themselves.

This pattern is sometimes called an "Anemic Domain Model." For this particular example, the domain complexity is relatively simple and doesn't justify implementing a Rich Domain Model with business logic embedded in the aggregate entities.

```plantuml
@startuml
class Customer << aggregate >> {
Customer entity
--
String name
String email
Address[] addresses
--
@OneToMany paymentMethods
}

    Customer *--down- Address
    class Address  {
Stored in a JSON column in the database.
--
String street
String city
}

    Customer o--down- PaymentMethod
    class PaymentMethod  {
PaymentMethodType type
String cardNumber
--
@ManyToOne customer
}

    PaymentMethod --down-> PaymentMethodType
    enum PaymentMethodType {
VISA(1)
MASTERCARD(2)
}

@enduml
```

### REST API defined with OpenAPI

With these REST Endpoints:

[https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml)

![OpenAPI Endpoints](https://github.com/ZenWave360/zenwave-playground/raw/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/endpoints-screenshot.png)

### Externalized Domain Events with AsyncAPI

And these Domain Events published to a Kafka Topic:

[https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml)

![AsyncAPI Operations](https://github.com/ZenWave360/zenwave-playground/raw/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi-operations.png)

## Building with ZenWave Domain Model and SDK

When modeling a microservice with ZenWave SDK we usually do it using two main files:

- A `zenwave-model.zdl` file containing the domain model and service definitions, we use this file to iterate and refine the domain model.
- A `zenwave-scripts.zw` file containing the plugin configurations and executions, you can run each plugin individually from [ZenWave Model Editor for IntelliJ](https://www.zenwave360.io/zenwave-platform.md) to generate different aspects of the application.

The full application we are building in this example was defined in the following ZDL model:

**\`zenwave-model.zdl\` for Customer Master Data Service** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl)

```zdl
/**
 * Sample ZenWave Model Definition.
 * Use zenwave-scripts.zdl to generate your code from this model definition.
 */
config {
    title "ZenWave Customer JPA Example"
    basePackage "io.zenwave360.example"
    persistence jpa
    databaseType postgresql

    layout CleanHexagonalProjectLayout

    // these should match the values of openapi-generator-maven-plugin
    // used by the OpenAPIControllersPlugin and SpringWebTestClientPlugin
    openApiApiPackage "{{basePackage}}.adapters.web"
    openApiModelPackage "{{basePackage}}.adapters.web.model"
    openApiModelNameSuffix DTO
}

/**
* Customer entity
*/
@aggregate
@auditing // adds auditing fields to the entity
entity Customer {
    name String required maxlength(254) /** Customer name */
    email String required maxlength(254) pattern(/^[^@]+@[^\\s@]+\\.[^\\s@]+$/)
    /** Customer Addresses can be stored in a JSON column in the database. */
    @json addresses Address[] minlength(1) maxlength(5) {
        street String required maxlength(254)
        city String required maxlength(254)
    }
}

@auditing
entity PaymentMethod {
    type PaymentMethodType required
    cardNumber String required
}

enum PaymentMethodType { VISA(1), MASTERCARD(2) }

relationship OneToMany {
    Customer{paymentMethods required maxlength(3)} to PaymentMethod{customer required}
}

// you can create 'inputs' as dtos for your service methods, or use entities directly
input CustomerSearchCriteria {
    name String
    email String
    city String
    state String
}

@rest("/customers")
service CustomerService for (Customer) {
    @post
    createCustomer(Customer) Customer withEvents CustomerEvent
    @get("/{id}")
    getCustomer(id) Customer?
    @put("/{id}")
    updateCustomer(id, Customer) Customer? withEvents CustomerEvent
    @delete("/{id}")
    deleteCustomer(id) withEvents CustomerDeletedEvent
    @post(path: "/search", status: 200)
    @paginated
    searchCustomers(CustomerSearchCriteria) Customer[]
}

@copy(Customer)
@asyncapi({ channel: "CustomersChannel", topic: "customers" })
event CustomerEvent {
    id Long required
    version Integer
    // all fields from Customer are copied here, but not relationships
    paymentMethods PaymentMethod[]
}

@asyncapi({ channel: "CustomersChannel", topic: "customers" })
event CustomerDeletedEvent {
    id Long required
}
```

**\`zenwave-scripts.zw\` for Customer Master Data Service** - `examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw)

```zdl
config {
    zdlFile "zenwave-model.zdl"

    plugins {

        ZDLToOpenAPIPlugin {
            idType integer
            idTypeFormat int64
            targetFile "src/main/resources/public/apis/openapi.yml"
        }

        ZDLToAsyncAPIPlugin {
            asyncapiVersion v3
            schemaFormat avro
            avroPackage "io.zenwave360.example.core.outbound.events.dtos"
            idType long
            targetFile "src/main/resources/public/apis/asyncapi.yml"
            includeKafkaCommonHeaders true
            includeCloudEventsHeaders true
        }

        BackendApplicationDefaultPlugin {
            useLombok true
            includeEmitEventsImplementation true
            // --force // overwite all files
        }

        OpenAPIControllersPlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
        }

        SpringWebTestClientPlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
        }

        SpringWebTestClientPlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
            groupBy businessFlow
            businessFlowTestName CreateUpdateDeleteCustomerIntegrationTest
            operationIds createCustomer,updateCustomer,deleteCustomer,getCustomer
        }

        OpenAPIKaratePlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
        }

        OpenAPIKaratePlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
            groupBy businessFlow
            businessFlowTestName CreateUpdateDeleteCustomerKarateTest
            operationIds createCustomer,updateCustomer,deleteCustomer,getCustomer
        }
    }
}
```

> NOTE: You can name this files as you wish, just mind the file extension `.zdl` for the domain model and `.zw` for the scripts and in `.zw` pointing to the proper `zdlFile` file containing the domain model.

So let's dive into the details of how this application was built using ZenWave SDK.

### Model Configuration

Let's start with the configuration section of the ZDL model:

**ZenWave Model Configuration for Customer Master Data Service** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 1-18), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L1-L18)

```zdl
/**
 * Sample ZenWave Model Definition.
 * Use zenwave-scripts.zdl to generate your code from this model definition.
 */
config {
    title "ZenWave Customer JPA Example"
    basePackage "io.zenwave360.example"
    persistence jpa
    databaseType postgresql

    layout CleanHexagonalProjectLayout

    // these should match the values of openapi-generator-maven-plugin
    // used by the OpenAPIControllersPlugin and SpringWebTestClientPlugin
    openApiApiPackage "{{basePackage}}.adapters.web"
    openApiModelPackage "{{basePackage}}.adapters.web.model"
    openApiModelNameSuffix DTO
}
```

Basic settings:

- `title` and `basePackage` are self-explanatory and used throughout ZenWave SDK plugins for code and documentation generation.
- `persistence` tells the `BackendApplicationDefaultPlugin` which data store to target (`jpa` or `mongodb`), generating the appropriate Spring Data interfaces and controlling entity ID data types.
- `databaseType` works with `jpa` persistence to generate proper Hibernate configuration for ID generation strategies.
- `layout` determines the architectural structure generated by `BackendApplicationDefaultPlugin`. The `CleanHexagonalProjectLayout` creates a clean/hexagonal architecture with distinct layers: core domain, web adapters, and infrastructure. Note that JPA repository implementations are auto-generated by Spring Data, so no manual repository code is needed.

Additional configurations customizing the project layout:

- `openApiApiPackage`, `openApiModelPackage`, and `openApiModelNameSuffix` are used by the `OpenAPIControllersPlugin` and should match the values configured in the `openapi-generator-maven-plugin` in the `pom.xml` file.

**OpenAPI Generator Maven Plugin Configuration in pom.xml** - `examples/transactional-outbox-modulith-jpa/pom.xml` (lines 384-420), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/pom.xml#L384-L420)

```xml
			<plugin>
				<groupId>org.openapitools</groupId>
				<artifactId>openapi-generator-maven-plugin</artifactId>
				<version>${openapi-generator-maven-plugin.version}</version>
				<executions>
					<execution>
						<goals>
							<goal>generate</goal>
						</goals>
						<phase>generate-sources</phase>
                        <configuration>
                            <inputSpec>${project.basedir}/src/main/resources/public/apis/openapi.yml</inputSpec>
                            <skipIfSpecIsUnchanged>true</skipIfSpecIsUnchanged>
                            <generatorName>spring</generatorName>
                            <apiPackage>${openApiApiPackage}</apiPackage>
                            <modelPackage>${openApiModelPackage}</modelPackage>
                            <modelNameSuffix>DTO</modelNameSuffix>
                            <addCompileSourceRoot>true</addCompileSourceRoot>
                            <generateSupportingFiles>false</generateSupportingFiles>
                            <typeMappings>
                                <typeMapping>Double=java.math.BigDecimal</typeMapping>
                            </typeMappings>
                            <configOptions>
                                <useSpringBoot3>true</useSpringBoot3>
                                <documentationProvider>none</documentationProvider>
                                <openApiNullable>false</openApiNullable>
                                <useOptional>false</useOptional>
                                <useTags>true</useTags>
                                <interfaceOnly>true</interfaceOnly>
                                <skipDefaultInterface>true</skipDefaultInterface>
                                <delegatePattern>false</delegatePattern>
                                <sortParamsByRequiredFlag>false</sortParamsByRequiredFlag>
                            </configOptions>
                        </configuration>
					</execution>
				</executions>
			</plugin>
```

### Domain Modeling

Domain modeling starts with the `entity` declarations. Entities body contains fields, nested entities. `id` and `version` fields are added automatically to entities. Entities decorated with `@auditing` will also have `createdDate`, `createdBy`, `lastModifiedDate`, and `lastModifiedBy` fields added automatically.

Entities decorated with `@aggregate` are considered the root of an aggregate and a Spring Data repository is generated for them and can be used on `services`.

Nested entities are equivalente to entities decorated with `@embedded` which are not persisted separately, they are part of the aggregate root entity:

- In `mongodb` they are stored as nested documents, and they don't have an id or version fields.
- In `jpa` they are stored either as `@Embeddable` or as a JSON column in the database. In this particular example, we are using a JSON column to store the `addresses` array in the `Customer` entity. (Arrays are not supported as `@Embeddable` in JPA)

Relationships are modeled following JHipster JDL syntax and the corresponding fields are added to entities. In DDD, relationships between aggregates should typically be mapped only by their id. ZenWave SDK allows you to use `@OneToXXX` relationships between aggregates, which are mapped by their id and include a read-only reference to the related entity, enabling a richer domain model in the ZDL while maintaining DDD principles. This pattern is not used in this example, but it's good to know this capability exists.

**ZenWave Domain Model for Customer Master Data Service** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 20-46), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L20-L46)

```zdl
/**
* Customer entity
*/
@aggregate
@auditing // adds auditing fields to the entity
entity Customer {
    name String required maxlength(254) /** Customer name */
    email String required maxlength(254) pattern(/^[^@]+@[^\\s@]+\\.[^\\s@]+$/)
    /** Customer Addresses can be stored in a JSON column in the database. */
    @json addresses Address[] minlength(1) maxlength(5) {
        street String required maxlength(254)
        city String required maxlength(254)
    }
}

@auditing
entity PaymentMethod {
    type PaymentMethodType required
    cardNumber String required
}

enum PaymentMethodType { VISA(1), MASTERCARD(2) }

relationship OneToMany {
    Customer{paymentMethods required maxlength(3)} to PaymentMethod{customer required}
}
```

**Customer Entity Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/Customer.java` (lines 22-113), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/Customer.java#L22-L113)

```java
@lombok.Getter
@lombok.Setter
@Entity
@Table(name = "customer")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@EntityListeners(AuditingEntityListener.class)
public class Customer implements Serializable {

    @java.io.Serial
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Version
    private Integer version;

    /** Customer name */
    @NotNull
    @Size(max = 254)
    @Column(name = "name", nullable = false, length = 254)
    private String name;

    @NotNull
    @Size(max = 254)
    @Pattern(regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")
    @Column(name = "email", nullable = false, length = 254)
    private String email;

    /** Customer Addresses can be stored in a JSON column in the database. */
    @Size(min = 1, max = 5)
    @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON)
    @Column(name = "addresses")
    private List<Address> addresses = new ArrayList<>();

    @NotNull
    @Size(max = 3)
    @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private Set<PaymentMethod> paymentMethods = new HashSet<>();

    @CreatedBy
    @Column(name = "created_by", updatable = false)
    protected String createdBy;

    @CreatedDate
    @Column(name = "created_date", columnDefinition = "TIMESTAMP", updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    @Column(name = "last_modified_by")
    protected String lastModifiedBy;

    @LastModifiedDate
    @Column(name = "last_modified_date", columnDefinition = "TIMESTAMP")
    protected LocalDateTime lastModifiedDate;

    // manage relationships
    public Customer addPaymentMethods(PaymentMethod paymentMethods) {
        this.paymentMethods.add(paymentMethods);
        paymentMethods.setCustomer(this);
        return this;
    }

    public Customer removePaymentMethods(PaymentMethod paymentMethods) {
        this.paymentMethods.remove(paymentMethods);
        paymentMethods.setCustomer(null);
        return this;
    }

    /*
     * https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-
     * with-jpa-and-hibernate/
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) o;
        return getId() != null && getId().equals(other.getId());
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}
```

**Address Nested Entity Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/Address.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/Address.java)

```java
package io.zenwave360.example.core.domain;

import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.io.Serializable;

/** */
@lombok.Getter
@lombok.Setter
// @Embeddable // json embedded
public class Address implements Serializable {

    @java.io.Serial
    private static final long serialVersionUID = 1L;

    @NotNull
    @Size(max = 254)
    @Column(name = "street", nullable = false, length = 254)
    private String street;

    @NotNull
    @Size(max = 254)
    @Column(name = "city", nullable = false, length = 254)
    private String city;
}
```

**PaymentMethod Nested Entity Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/PaymentMethod.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/PaymentMethod.java)

```java
package io.zenwave360.example.core.domain;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

/** */
@lombok.Getter
@lombok.Setter
@Entity
@Table(name = "payment_method")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@EntityListeners(AuditingEntityListener.class)
public class PaymentMethod implements Serializable {

    @java.io.Serial
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Version
    private Integer version;

    @NotNull
    @Column(name = "type", nullable = false)
    @Convert(converter = PaymentMethodType.PaymentMethodTypeConverter.class)
    private PaymentMethodType type;

    @NotNull
    @Column(name = "card_number", nullable = false)
    private String cardNumber;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @CreatedBy
    @Column(name = "created_by", updatable = false)
    protected String createdBy;

    @CreatedDate
    @Column(name = "created_date", columnDefinition = "TIMESTAMP", updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    @Column(name = "last_modified_by")
    protected String lastModifiedBy;

    @LastModifiedDate
    @Column(name = "last_modified_date", columnDefinition = "TIMESTAMP")
    protected LocalDateTime lastModifiedDate;

    /*
     * https://vladmihalcea.com/the-best-way-to-implement-equals-hashcode-and-tostring-
     * with-jpa-and-hibernate/
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof PaymentMethod)) {
            return false;
        }
        PaymentMethod other = (PaymentMethod) o;
        return getId() != null && getId().equals(other.getId());
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}
```

Enums are also generated as Java enums, with an autogenerated JPA `AttributeConverter` which persists the enum the integer configured as `enumValue` in the ZDL model.

**PaymentMethodType Enum Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/PaymentMethodType.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/domain/PaymentMethodType.java)

```java
package io.zenwave360.example.core.domain;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.util.Arrays;

/** Enum for PaymentMethodType. */
public enum PaymentMethodType {
    VISA(1),
    MASTERCARD(2),
    ;

    private final Integer value;

    private PaymentMethodType(Integer value) {
        this.value = value;
    }

    public Integer getValue() {
        return value;
    }

    public static PaymentMethodType fromValue(Integer value) {
        return Arrays.stream(PaymentMethodType.values())
                .filter(e -> e.value.equals(value))
                .findFirst()
                .orElse(null);
    }

    @Converter
    static class PaymentMethodTypeConverter implements AttributeConverter<PaymentMethodType, Integer> {

        @Override
        public Integer convertToDatabaseColumn(PaymentMethodType attribute) {
            if (attribute == null) {
                return null;
            }

            return attribute.value;
        }

        @Override
        public PaymentMethodType convertToEntityAttribute(Integer dbData) {
            return PaymentMethodType.fromValue(dbData);
        }
    }
}
```

Aggregates will also get generated a Spring Data Repository interface and an InMemory implementation for testing purposes.

**CustomerRepository.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/outbound/jpa/CustomerRepository.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/outbound/jpa/CustomerRepository.java)

```java
package io.zenwave360.example.core.outbound.jpa;

import io.zenwave360.example.core.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/** Spring Data JPA repository for the Customer entity. */
@SuppressWarnings("unused")
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
```

**InMemoryCustomerRepository.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/inmemory/CustomerRepositoryInMemory.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/inmemory/CustomerRepositoryInMemory.java)

```java
package io.zenwave360.example.infrastructure.jpa.inmemory;

import static org.apache.commons.lang3.ObjectUtils.firstNonNull;

import io.zenwave360.example.core.domain.Customer;
import io.zenwave360.example.core.outbound.jpa.CustomerRepository;

public class CustomerRepositoryInMemory extends InMemoryJpaRepository<Customer> implements CustomerRepository {

    private long nextId = 0;
    private final PrimaryKeyGenerator<Long> primaryKeyGenerator = () -> nextId++;

    public Customer save(Customer entity) {
        entity = super.save(entity);
        entity.getPaymentMethods().forEach(paymentMethod -> {
            paymentMethod.setId(firstNonNull(paymentMethod.getId(), primaryKeyGenerator.next()));
        });
        return entity;
    }
}
```

### Services

Services are the entry point to the core domain, and are generated as Spring `@Service` classes.

**Customer Service for (Customer)** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 55-68), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L55-L68)

```zdl
@rest("/customers")
service CustomerService for (Customer) {
    @post
    createCustomer(Customer) Customer withEvents CustomerEvent
    @get("/{id}")
    getCustomer(id) Customer?
    @put("/{id}")
    updateCustomer(id, Customer) Customer? withEvents CustomerEvent
    @delete("/{id}")
    deleteCustomer(id) withEvents CustomerDeletedEvent
    @post(path: "/search", status: 200)
    @paginated
    searchCustomers(CustomerSearchCriteria) Customer[]
}
```

This will generate a `CustomerService`, a `CustomerServiceImpl` referencing `CustomerRepository` (because it's this service`@aggregate` entity) and `CustomerServiceTest` that uses an in-memory implementation of the repository for testing.

**CustomerService.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/inbound/CustomerService.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/inbound/CustomerService.java)

```java
package io.zenwave360.example.core.inbound;

import io.zenwave360.example.core.domain.Customer;
import io.zenwave360.example.core.inbound.dtos.CustomerSearchCriteria;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/** Inbound Service Port for managing [Customer]. */
public interface CustomerService {

    /** With Events: [CustomerEvent]. */
    public Customer createCustomer(Customer input);

    /** */
    public Optional<Customer> getCustomer(Long id);

    /** With Events: [CustomerEvent]. */
    public Optional<Customer> updateCustomer(Long id, Customer input);

    /** With Events: [CustomerEvent]. */
    public void deleteCustomer(Long id);

    /** */
    public Page<Customer> searchCustomers(CustomerSearchCriteria input, Pageable pageable);
}
```

**CustomerServiceImpl.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/implementation/CustomerServiceImpl.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/implementation/CustomerServiceImpl.java)

```java
package io.zenwave360.example.core.implementation;

import io.zenwave360.example.core.domain.Customer;
import io.zenwave360.example.core.implementation.mappers.CustomerServiceMapper;
import io.zenwave360.example.core.implementation.mappers.EventsMapper;
import io.zenwave360.example.core.inbound.CustomerService;
import io.zenwave360.example.core.inbound.dtos.CustomerSearchCriteria;
import io.zenwave360.example.core.outbound.events.CustomerEventsProducer;
import io.zenwave360.example.core.outbound.jpa.CustomerRepository;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/** Service Implementation for managing [Customer]. */
@Service
@Transactional(readOnly = true)
@lombok.AllArgsConstructor
public class CustomerServiceImpl implements CustomerService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final CustomerServiceMapper customerServiceMapper = CustomerServiceMapper.INSTANCE;

    private final CustomerRepository customerRepository;

    private final EventsMapper eventsMapper = EventsMapper.INSTANCE;

    private final CustomerEventsProducer eventsProducer;

    private final ApplicationEventPublisher applicationEventPublisher;

    @Transactional
    public Customer createCustomer(Customer input) {
        log.debug("[CRUD] Request to save Customer: {}", input);
        var customer = customerServiceMapper.update(new Customer(), input);
        customer = customerRepository.save(customer);
        // TODO: may need to reload the entity to fetch relationships 'mapped by id'
        // emit events
        var customerEvent = eventsMapper.asCustomerEvent(customer);
        eventsProducer.onCustomerEvent(customerEvent);
        return customer;
    }

    public Optional<Customer> getCustomer(Long id) {
        log.debug("[CRUD] Request to get Customer : {}", id);
        var customer = customerRepository.findById(id);
        return customer;
    }

    @Transactional
    public Optional<Customer> updateCustomer(Long id, Customer input) {
        log.debug("Request updateCustomer: {} {}", id, input);

        var customer = customerRepository
                .findById(id)
                .map(existingCustomer -> {
                    return customerServiceMapper.update(existingCustomer, input);
                })
                .map(customerRepository::save);
        if (customer.isPresent()) {
            // emit events
            var customerEvent = eventsMapper.asCustomerEvent(customer.get());
            eventsProducer.onCustomerEvent(customerEvent);
        }
        return customer;
    }

    @Transactional
    public void deleteCustomer(Long id) {
        log.debug("[CRUD] Request to delete Customer : {}", id);
        customerRepository.deleteById(id);
        // emit events
        var customerEvent = eventsMapper.asCustomerEvent(id);
        eventsProducer.onCustomerDeletedEvent(customerEvent);
    }

    public Page<Customer> searchCustomers(CustomerSearchCriteria input, Pageable pageable) {
        log.debug("Request searchCustomers: {} {}", input, pageable);

        var customers = customerRepository.findAll(pageable);
        return customers;
    }
}
```

**CustomerServiceTest.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/core/implementation/CustomerServiceTest.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/core/implementation/CustomerServiceTest.java)

```java
package io.zenwave360.example.core.implementation;

import static org.junit.jupiter.api.Assertions.*;

import io.zenwave360.example.config.ServicesInMemoryConfig;
import io.zenwave360.example.core.domain.Address;
import io.zenwave360.example.core.domain.Customer;
import io.zenwave360.example.core.inbound.dtos.CustomerSearchCriteria;
import io.zenwave360.example.infrastructure.jpa.inmemory.CustomerRepositoryInMemory;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;

/** Acceptance Test for CustomerService. */
class CustomerServiceTest {

    private final Logger log = LoggerFactory.getLogger(getClass());

    ServicesInMemoryConfig context = new ServicesInMemoryConfig();

    CustomerServiceImpl customerService = context.customerService();

    CustomerRepositoryInMemory customerRepository = context.customerRepository();

    @BeforeEach
    void setUp() {
        context.reloadTestData();
    }

    @Test
    void createCustomerTest() {
        var input = new Customer();
        input.setName("name");
        input.setEmail("me@email.com");
        input.setAddresses(List.of(
                new Address() //
                        .setStreet("street")
                        .setCity("city")));
        var customer = customerService.createCustomer(input);
        assertNotNull(customer.getId());
        assertTrue(customerRepository.containsEntity(customer));
    }

    @Test
    void getCustomerTest() {
        var id = 1L; // TODO fill id
        var customer = customerService.getCustomer(id);
        assertTrue(customer.isPresent());
    }

    @Test
    void updateCustomerTest() {
        var id = 1L; // TODO fill id
        var input = new Customer();
        input.setName("name");
        input.setEmail("me@email.com");
        input.setAddresses(List.of(
                new Address() //
                        .setStreet("street")
                        .setCity("city")));
        assertTrue(customerRepository.containsKey(id));
        var customer = customerService.updateCustomer(id, input);
        assertTrue(customer.isPresent());
        assertTrue(customerRepository.containsEntity(customer.get()));
    }

    @Test
    void deleteCustomerTest() {
        var id = 1L; // TODO fill id
        assertTrue(customerRepository.containsKey(id));
        customerService.deleteCustomer(id);
        assertFalse(customerRepository.containsKey(id));
    }

    @Test
    void searchCustomersTest() {
        var searchCriteria = new CustomerSearchCriteria();
        var results = customerService.searchCustomers(searchCriteria, PageRequest.of(0, 10));
        Assertions.assertNotNull(results);
        Assertions.assertFalse(results.isEmpty());
    }
}
```

This `CustomerServiceTest` is just an skeleton, you will need to provide testing data and assertions.

### Unit and Integration Tests

ZenWave SDK generates a complete suit of both Unit and Integration Tests:

#### Core Integration Tests

`BackendApplicationDefaultPlugin` generates Integration Tests for `infrastructure` or `outbound adapter classes` (repositories in this case) that run as `@SpringBootTest` against TestContainers using [docker-compose.yml](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/docker-compose.yml) configuration.

These tests verify that JPA configuration and entity relationships are correctly mapped. As the developer, you need to populate tests with input data and assertions, and provide initial database state in the standard `src/test/resources/data.sql` file. These integration tests are transactional, so the database state is rolled back to its original state after each test.

**Testing JPA and relationshipst in CustomerRepositoryIntegrationTest.java** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/CustomerRepositoryIntegrationTest.java` (lines 39-64), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/CustomerRepositoryIntegrationTest.java#L39-L64)

```java
    @Test
    void saveTest() {
        Customer customer = new Customer();
        customer.setName("Jane Smith");
        customer.setEmail("jane.smith@example.com");
        customer.setAddresses(List.of(new Address().setStreet("456 Elm St").setCity("Othertown")));

        // OneToMany paymentMethods owner: true
        var paymentMethods = new PaymentMethod();
        paymentMethods.setType(PaymentMethodType.VISA);
        paymentMethods.setCardNumber("6543210987654321");
        customer.addPaymentMethods(paymentMethods);

        // Persist aggregate root
        var created = customerRepository.save(customer);

        // reloading to get relationships persisted by id
        entityManager.flush();
        entityManager.refresh(created);
        Assertions.assertNotNull(created.getId());
        Assertions.assertNotNull(created.getVersion());
        Assertions.assertNotNull(created.getCreatedBy());
        Assertions.assertNotNull(created.getCreatedDate());

        Assertions.assertTrue(customer.getPaymentMethods().stream().allMatch(item -> item.getId() != null));
    }
```

Remember to verify that Services list in `DockerComposeInitializer.java` match the services declared in `docker-compose.yml`, pay particular attention to the database service (`postgresql`, with database `app` in this example) and the Kafka and Schema Registry services used by the outbox.

**Services List in DockerComposeInitializer.java** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/config/DockerComposeInitializer.java` (lines 38-41), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/config/DockerComposeInitializer.java#L38-L41)

```java
    private static final List<Service> SERVICES = List.of(
            new Service("postgresql", 5432, "DATASOURCE_URL", "jdbc:postgresql://%s:%s/app"),
            new Service("kafka", 9092, "KAFKA_BOOTSTRAP_SERVERS", "%s:%s"),
            new Service("schema-registry", 8081, "SCHEMA_REGISTRY_URL", "http://%s:%s"));
```

`DockerComposeInitializer.java` contains the annotation required to start TestContainers in your `@SpringBootTest` tests:

`examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/BaseRepositoryIntegrationTest.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/infrastructure/jpa/BaseRepositoryIntegrationTest.java)

```java
package io.zenwave360.example.infrastructure.jpa;

import io.zenwave360.example.config.DockerComposeInitializer;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@ActiveProfiles("test")
@DockerComposeInitializer.EnableDockerCompose
@org.springframework.transaction.annotation.Transactional
public abstract class BaseRepositoryIntegrationTest {}
```

#### Core Unit Tests

`BackendApplicationDefaultPlugin` also generates Unit Tests for your core services that use InMemory Repository implementations (avoiding Mockito). It also generates a `ServicesInMemoryConfig.java` to provide service implementations wired with InMemory dependencies:

**Using ServicesInMemoryConfig.java in Service Tests** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/core/implementation/CustomerServiceTest.java` (lines 19-33), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/core/implementation/CustomerServiceTest.java#L19-L33)

```java
class CustomerServiceTest {

    private final Logger log = LoggerFactory.getLogger(getClass());

    ServicesInMemoryConfig context = new ServicesInMemoryConfig();

    CustomerServiceImpl customerService = context.customerService();

    CustomerRepositoryInMemory customerRepository = context.customerRepository();

    @BeforeEach
    void setUp() {
        context.reloadTestData();
    }
```

You can provide in-memory test data by creating JSON files in `src/test/resources/{{persistence}}/data/{{aggregateName}}/{{id}}.json` - these will populate the in-memory repository before each test runs.

`examples/transactional-outbox-modulith-jpa/src/test/resources/data/jpa/customer/1.json`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/resources/data/jpa/customer/1.json)

```json
{
  "id": 1,
  "version": 1,
  "email": "john.doe@example.com",
  "name": "John Doe",
  "addresses": [
    {
      "city": "Anytown",
      "street": "123 Main St"
    }
  ],
  "paymentMethods": [
    {
      "type": 1,
      "cardNumber": "1234567890123456",
      "createdBy": "system",
      "createdDate": "2023-01-01T00:00:00",
      "lastModifiedBy": "system",
      "lastModifiedDate": "2023-01-01T00:00:00"
    }
  ],
  "createdBy": "system",
  "createdDate": "2023-01-01T00:00:00",
  "lastModifiedBy": "system",
  "lastModifiedDate": "2023-01-01T00:00:00"
}
```

### Exposing a REST API for your Service

Services can be decorated with `@rest`, `@get`, `@post`, `@put`, `@delete`, `@patch` annotations to document how they will be exposed as REST endpoints. The `ZdlToOpenAPIPlugin` can generate a complete OpenAPI definition from these annotations, which you can then customize manually or by applying OpenAPI overlays during code generation.

The `ZdlToOpenAPIPlugin` will generate `#/components/schemas/**` for all entities, inputs and outputs used in your service commands. Additional annotations like `@fileupload` and `@filedownload` are available for file handling endpoints (see the [Clinical Tool - Modulith](https://www.zenwave360.io/docs/examples/ddd-examples/modulith-clinical-tool-jpa.md) example for details).

#### Create Customer Endpoint

When using the `ZDLToOpenAPIPlugin`, the following

**this service command:** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 57-58), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L57-L58)

```zdl
    @post
    createCustomer(Customer) Customer withEvents CustomerEvent
```

would produce this:

`examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml` (lines 27-44), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml#L27-L44)

```yaml
  /customers:
    post:
      operationId: createCustomer
      description: "createCustomer"
      tags: [Customer]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Customer"
      responses:
        "201":
          description: "OK"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Customer"
```

When using the `OpenAPIControllersPlugin`, the following

`examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml` (lines 27-44), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml#L27-L44)

```yaml
  /customers:
    post:
      operationId: createCustomer
      description: "createCustomer"
      tags: [Customer]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Customer"
      responses:
        "201":
          description: "OK"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Customer"
```

would produce this java code:

`examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/CustomerApiController.java` (lines 52-59), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/CustomerApiController.java#L52-L59)

```java
    @Override
    public ResponseEntity<CustomerDTO> createCustomer(CustomerDTO reqBody) {
        log.debug("REST request to createCustomer: {}", reqBody);
        var input = mapper.asCustomer(reqBody);
        var customer = customerService.createCustomer(input);
        CustomerDTO responseDTO = mapper.asCustomerDTO(customer);
        return ResponseEntity.status(201).body(responseDTO);
    }
```

And its corresponding:

**CustomerDTOsMapper.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/mappers/CustomerDTOsMapper.java` (lines 13-34), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/mappers/CustomerDTOsMapper.java#L13-L34)

```java
@Mapper(uses = BaseMapper.class)
public interface CustomerDTOsMapper {

    CustomerDTOsMapper INSTANCE = Mappers.getMapper(CustomerDTOsMapper.class);

    // request mappings
    CustomerSearchCriteria asCustomerSearchCriteria(CustomerSearchCriteriaDTO dto);

    Customer asCustomer(CustomerDTO dto);

    // response mappings

    List<CustomerDTO> asCustomerDTOList(List<Customer> entityList);

    CustomerPaginatedDTO asCustomerPaginatedDTO(Page<Customer> page);

    default Page<CustomerDTO> asCustomerDTOPage(Page<Customer> page) {
        return page.map(this::asCustomerDTO);
    }

    CustomerDTO asCustomerDTO(Customer entity);
}
```

**CustomerApiControllerTest.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java` (lines 26-35), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java#L26-L35)

```java
    @Test
    void createCustomerTest() {
        CustomerDTO reqBody = new CustomerDTO();
        reqBody.setName("John Doe");
        reqBody.setEmail("john.doe@example.com");
        reqBody.setAddresses(List.of(new AddressDTO("Anytown", "123 Main St")));
        reqBody.setPaymentMethods(List.of(new PaymentMethodDTO(PaymentMethodTypeDTO.VISA, "1234567890123456")));
        var response = controller.createCustomer(reqBody);
        Assertions.assertEquals(201, response.getStatusCode().value());
    }
```

> Remember that generated `Mappers` and `Tests` are provided as a starting point, you will need to adapt them to your needs.

#### Search Customer Endpoint

When using the `ZDLToOpenAPIPlugin`, the following

**sevice command \`@paginated\` and returning an aray:** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 65-67), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L65-L67)

```zdl
    @post(path: "/search", status: 200)
    @paginated
    searchCustomers(CustomerSearchCriteria) Customer[]
```

would produce this:

`examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml` (lines 102-123), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml#L102-L123)

```yaml
  /customers/search:
    post:
      operationId: searchCustomers
      description: "searchCustomers"
      tags: [Customer]
      parameters:
        - $ref: "#/components/parameters/page"
        - $ref: "#/components/parameters/limit"
        - $ref: "#/components/parameters/sort"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CustomerSearchCriteria"
      responses:
        "200":
          description: "OK"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CustomerPaginated"
```

When using the `OpenAPIControllersPlugin`, the previous OpenAPI definition:

`examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml` (lines 102-123), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/openapi.yml#L102-L123)

```yaml
  /customers/search:
    post:
      operationId: searchCustomers
      description: "searchCustomers"
      tags: [Customer]
      parameters:
        - $ref: "#/components/parameters/page"
        - $ref: "#/components/parameters/limit"
        - $ref: "#/components/parameters/sort"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CustomerSearchCriteria"
      responses:
        "200":
          description: "OK"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CustomerPaginated"
```

would produce this java code:

`examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/CustomerApiController.java` (lines 94-116), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/adapters/web/CustomerApiController.java#L94-L116)

```java
    public ResponseEntity<CustomerPaginatedDTO> searchCustomers(
            Integer page, Integer limit, List<String> sort, CustomerSearchCriteriaDTO reqBody) {
        log.debug("REST request to searchCustomers: {}, {}, {}, {}", page, limit, sort, reqBody);
        var input = mapper.asCustomerSearchCriteria(reqBody);
        var customerPage = customerService.searchCustomers(input, pageOf(page, limit, sort));
        var responseDTO = mapper.asCustomerPaginatedDTO(customerPage);
        return ResponseEntity.status(200).body(responseDTO);
    }

    protected Pageable pageOf(Integer page, Integer limit, List<String> sort) {
        Sort sortOrder = sort != null
                ? Sort.by(sort.stream()
                        .map(sortParam -> {
                            String[] parts = sortParam.split(":");
                            String property = parts[0];
                            Sort.Direction direction =
                                    parts.length > 1 ? Sort.Direction.fromString(parts[1]) : Sort.Direction.ASC;
                            return new Sort.Order(direction, property);
                        })
                        .toList())
                : Sort.unsorted();
        return PageRequest.of(page != null ? page : 0, limit != null ? limit : 10, sortOrder);
    }
```

And its corresponding:

**CustomerApiControllerTest.java Generated by ZenWave SDK** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java` (lines 63-71), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java#L63-L71)

```java
    @Test
    void searchCustomersTest() {
        Integer page = 0;
        Integer limit = 10;
        List<String> sort = List.of("name");
        CustomerSearchCriteriaDTO reqBody = new CustomerSearchCriteriaDTO();
        var response = controller.searchCustomers(page, limit, sort, reqBody);
        Assertions.assertEquals(200, response.getStatusCode().value());
    }
```

#### Web Adapters Unit Tests

`OpenAPIControllersPlugin` generates Spring MVC controllers that implement your OpenAPI specification, along with corresponding Unit Tests that use `ServicesInMemoryConfig.java` for dependency injection.

**Unit Testing Spring MVC Controllers** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java` (lines 12-36), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiControllerTest.java#L12-L36)

```java
/** Test controller for CustomerApiController. */
class CustomerApiControllerTest {

    private final Logger log = LoggerFactory.getLogger(getClass());

    ServicesInMemoryConfig context = new ServicesInMemoryConfig();

    CustomerApiController controller = new CustomerApiController(context.customerService());

    @BeforeEach
    void setUp() {
        context.reloadTestData();
    }

    @Test
    void createCustomerTest() {
        CustomerDTO reqBody = new CustomerDTO();
        reqBody.setName("John Doe");
        reqBody.setEmail("john.doe@example.com");
        reqBody.setAddresses(List.of(new AddressDTO("Anytown", "123 Main St")));
        reqBody.setPaymentMethods(List.of(new PaymentMethodDTO(PaymentMethodTypeDTO.VISA, "1234567890123456")));
        var response = controller.createCustomer(reqBody);
        Assertions.assertEquals(201, response.getStatusCode().value());
    }
```

You can disable controller Unit Test generation if you prefer to test your REST API through HTTP calls instead of testing the Java controllers directly.

### Web Adapters Integration Tests with Spring WebTestClient

If you prefer to test your REST API via HTTP semantics you can use `SpringWebTestClientPlugin` to generate both single endpoint tests as well as business flows spaning multiple endpoints:

When using the `SpringWebTestClientPlugin`, the following

`examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw` (lines 32-34), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw#L32-L34)

```zdl
        SpringWebTestClientPlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
        }
```

would produce this API test:

**CustomerApiIntegrationTest** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiIntegrationTest.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CustomerApiIntegrationTest.java)

```java
package io.zenwave360.example.adapters.web;

import static org.springframework.http.HttpMethod.*;

import io.zenwave360.example.adapters.web.model.CustomerSearchCriteriaDTO;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;

/**
 * Integration tests for the {@link CustomerApi} REST controller.
 */
class CustomerApiIntegrationTest extends BaseWebTestClientTest {

    /**
     * Test: createCustomer for OK.
     */
    @Test
    void testCreateCustomer_201() {
        var requestBody =
                """
                {
                  "email": "jane.doe@example.com",
                  "name": "Jane Doe",
                  "addresses": [
                    {
                      "city": "Othertown",
                      "street": "456 Elm St"
                    }
                  ],
                  "paymentMethods": [
                    {
                      "type": "VISA",
                      "cardNumber": "6543210987654321"
                    }
                  ]
                }
                """;

        webTestClient
                .method(POST)
                .uri("/api/customers")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .exchange()
                .expectStatus()
                .isEqualTo(201)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .expectBody()
                .jsonPath("$.id")
                .isNotEmpty()
                .jsonPath("$.version")
                .isNotEmpty()
                .jsonPath("$.name")
                .isNotEmpty()
                .jsonPath("$.email")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isArray()
                .jsonPath("$.addresses[0].street")
                .isNotEmpty()
                .jsonPath("$.addresses[0].city")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isArray()
                .jsonPath("$.paymentMethods[0].id")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].version")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].type")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].cardNumber")
                .isNotEmpty();
    }

    /**
     * Test: getCustomer for OK.
     */
    @Test
    void testGetCustomer_200() {
        var id = "1";

        webTestClient
                .method(GET)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isEqualTo(200)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .expectBody()
                .jsonPath("$.id")
                .isNotEmpty()
                .jsonPath("$.version")
                .isNotEmpty()
                .jsonPath("$.name")
                .isNotEmpty()
                .jsonPath("$.email")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isArray()
                .jsonPath("$.addresses[0].street")
                .isNotEmpty()
                .jsonPath("$.addresses[0].city")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isArray()
                .jsonPath("$.paymentMethods[0].id")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].version")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].type")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].cardNumber")
                .isNotEmpty();
    }

    /**
     * Test: updateCustomer for OK.
     */
    @Test
    void testUpdateCustomer_200() {
        var id = "1";
        var requestBody =
                """
                {
                  "id": 1,
                  "version": 1,
                  "email": "john.doe@example.com",
                  "name": "John Doe",
                  "addresses": [
                    {
                      "city": "Anytown",
                      "street": "123 Main St"
                    }
                  ],
                  "paymentMethods": [
                    {
                      "type": "VISA",
                      "customerId": 1,
                      "cardNumber": "1234567890123456"
                    }
                  ]
                }
                """;

        webTestClient
                .method(PUT)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .exchange()
                .expectStatus()
                .isEqualTo(200)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .expectBody()
                .jsonPath("$.id")
                .isNotEmpty()
                .jsonPath("$.version")
                .isNotEmpty()
                .jsonPath("$.name")
                .isNotEmpty()
                .jsonPath("$.email")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isNotEmpty()
                .jsonPath("$.addresses")
                .isArray()
                .jsonPath("$.addresses[0].street")
                .isNotEmpty()
                .jsonPath("$.addresses[0].city")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isNotEmpty()
                .jsonPath("$.paymentMethods")
                .isArray()
                .jsonPath("$.paymentMethods[0].id")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].version")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].type")
                .isNotEmpty()
                .jsonPath("$.paymentMethods[0].cardNumber")
                .isNotEmpty();
    }

    /**
     * Test: deleteCustomer for OK.
     */
    @Test
    void testDeleteCustomer_204() {
        var id = "1";

        webTestClient
                .method(DELETE)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isEqualTo(204);
    }

    /**
     * Test: searchCustomers for OK.
     */
    @Test
    void testSearchCustomers_200() {
        CustomerSearchCriteriaDTO requestBody = new CustomerSearchCriteriaDTO();
        requestBody.setName("Jane Doe");
        requestBody.setEmail("jane.doe@example.com");
        requestBody.setCity("Othertown");
        requestBody.setState("NY");
        var page = "0";
        var limit = "10";
        var sort = "name:asc";

        webTestClient
                .method(POST)
                .uri(uriBuilder -> uriBuilder
                        .path("/api/customers/search")
                        .queryParam("page", page)
                        .queryParam("limit", limit)
                        .queryParam("sort", sort)
                        .build(page, limit, sort))
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .exchange()
                .expectStatus()
                .isEqualTo(200)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .expectBody()
                .jsonPath("$.totalPages")
                .isNotEmpty()
                .jsonPath("$.number")
                .isNotEmpty()
                .jsonPath("$.numberOfElements")
                .isNotEmpty()
                .jsonPath("$.size")
                .isNotEmpty()
                .jsonPath("$.content")
                .isNotEmpty()
                .jsonPath("$.content")
                .isArray()
                .jsonPath("$.content[0].id")
                .isNotEmpty()
                .jsonPath("$.content[0].version")
                .isNotEmpty()
                .jsonPath("$.content[0].name")
                .isNotEmpty()
                .jsonPath("$.content[0].email")
                .isNotEmpty()
                .jsonPath("$.content[0].addresses")
                .isNotEmpty()
                .jsonPath("$.content[0].paymentMethods")
                .isNotEmpty()
                .jsonPath("$.totalElements")
                .isNotEmpty();
    }
}
```

When using the `SpringWebTestClientPlugin`, the following

`examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw` (lines 36-41), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw#L36-L41)

```zdl
        SpringWebTestClientPlugin {
            openapiFile "src/main/resources/public/apis/openapi.yml"
            groupBy businessFlow
            businessFlowTestName CreateUpdateDeleteCustomerIntegrationTest
            operationIds createCustomer,updateCustomer,deleteCustomer,getCustomer
        }
```

would produce this Business Flow API test:

**CreateUpdateDeleteCustomerIntegrationTest** - `examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CreateUpdateDeleteCustomerIntegrationTest.java`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/CreateUpdateDeleteCustomerIntegrationTest.java)

```java
package io.zenwave360.example.adapters.web;

import static org.springframework.http.HttpMethod.*;

import io.zenwave360.example.adapters.web.model.CustomerDTO;
import io.zenwave360.example.adapters.web.model.PaymentMethodTypeDTO;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;

/**
 * Business Flow Test for: createCustomer, getCustomer, updateCustomer, deleteCustomer.
 */
class CreateUpdateDeleteCustomerIntegrationTest extends BaseWebTestClientTest {

    /**
     * Business Flow Test for: createCustomer, getCustomer, updateCustomer, deleteCustomer.
     */
    @Test
    void testCreateUpdateDeleteCustomerIntegrationTest() {
        // createCustomer: createCustomer
        var customerRequestBody0 =
                """
                {
                  "email": "jane.doe@example.com",
                  "name": "Jane Doe",
                  "addresses": [
                    {
                      "city": "Othertown",
                      "street": "456 Elm St"
                    }
                  ],
                  "paymentMethods": [
                    {
                      "type": "VISA",
                      "cardNumber": "6543210987654321"
                    }
                  ]
                }
                """;

        var createCustomerResponse0 = webTestClient
                .method(POST)
                .uri("/api/customers")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(customerRequestBody0)
                .exchange()
                .expectStatus()
                .isEqualTo(201)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .returnResult(CustomerDTO.class);

        // getCustomer: getCustomer
        var id = createCustomerResponse0.getResponseBody().blockFirst().getId();

        var getCustomerResponse1 = webTestClient
                .method(GET)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isEqualTo(200)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .returnResult(CustomerDTO.class);

        // updateCustomer: updateCustomer
        CustomerDTO customerRequestBody2 =
                getCustomerResponse1.getResponseBody().blockFirst();
        customerRequestBody2.setName("updated");
        customerRequestBody2.setEmail("updated@email.com");
        customerRequestBody2.getPaymentMethods().get(0).setType(PaymentMethodTypeDTO.VISA);

        var updateCustomerResponse2 = webTestClient
                .method(PUT)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(customerRequestBody2)
                .exchange()
                .expectStatus()
                .isEqualTo(200)
                .expectHeader()
                .contentType(MediaType.APPLICATION_JSON)
                .returnResult(CustomerDTO.class);

        // deleteCustomer: deleteCustomer

        webTestClient
                .method(DELETE)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isEqualTo(204);

        // getCustomer: getCustomer (not found)
        webTestClient
                .method(GET)
                .uri("/api/customers/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus()
                .isEqualTo(404);
    }
}
```

You can control whether these are Unit or Integration Tests with `@SpringBootTest` in

`examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/BaseWebTestClientTest.java` (lines 13-29), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/adapters/web/BaseWebTestClientTest.java#L13-L29)

```java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@ActiveProfiles("test")
@DockerComposeInitializer.EnableDockerCompose
@org.springframework.transaction.annotation.Transactional
public abstract class BaseWebTestClientTest {

    @Autowired
    protected WebApplicationContext context;

    protected WebTestClient webTestClient;

    @BeforeEach
    void setup() {
        this.webTestClient =
                MockMvcWebTestClient.bindToApplicationContext(this.context).build();
    }
}
```

As always, it's your responsibility as the developer to provide test data and parameters that match the initial state, whether you're using a containerized database or an in-memory implementation.

### Publishing Domain Events with AsyncAPI

You service commands can publish Domain Events as part of their operative using `withEvent` keyword:

When using `withEvents` in service commands

`examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 61-62), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L61-L62)

```zdl
    @put("/{id}")
    updateCustomer(id, Customer) Customer? withEvents CustomerEvent
```

would produce generate and use an EventsProvider in your service implementation:

`examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/implementation/CustomerServiceImpl.java` (lines 55-71), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/core/implementation/CustomerServiceImpl.java#L55-L71)

```java
    @Transactional
    public Optional<Customer> updateCustomer(Long id, Customer input) {
        log.debug("Request updateCustomer: {} {}", id, input);

        var customer = customerRepository
                .findById(id)
                .map(existingCustomer -> {
                    return customerServiceMapper.update(existingCustomer, input);
                })
                .map(customerRepository::save);
        if (customer.isPresent()) {
            // emit events
            var customerEvent = eventsMapper.asCustomerEvent(customer.get());
            eventsProducer.onCustomerEvent(customerEvent);
        }
        return customer;
    }
```

You can control whether you want to keep you Domain Events internal to your application or publish them to an external broker and documented using AsyncAPI:

**Domain Events decorated with @asyncapi in ZDL** - `examples/transactional-outbox-modulith-jpa/zenwave-model.zdl` (lines 70-82), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-model.zdl#L70-L82)

```zdl
@copy(Customer)
@asyncapi({ channel: "CustomersChannel", topic: "customers" })
event CustomerEvent {
    id Long required
    version Integer
    // all fields from Customer are copied here, but not relationships
    paymentMethods PaymentMethod[]
}

@asyncapi({ channel: "CustomersChannel", topic: "customers" })
event CustomerDeletedEvent {
    id Long required
}
```

Events decorated with `@asyncapi` when running `ZDLToAsyncAPIPlugin`

`examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw` (lines 12-20), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/zenwave-scripts.zw#L12-L20)

```zdl
        ZDLToAsyncAPIPlugin {
            asyncapiVersion v3
            schemaFormat avro
            avroPackage "io.zenwave360.example.core.outbound.events.dtos"
            idType long
            targetFile "src/main/resources/public/apis/asyncapi.yml"
            includeKafkaCommonHeaders true
            includeCloudEventsHeaders true
        }
```

would generate a complete asyncapi.yml file (in this case, based in plugin configuration, including avro schemas `avro/*.avsc`)

`examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml`, [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml)

```yaml
asyncapi: 3.0.0
info:
  title: "ZenWave Customer JPA Example"
  version: 0.0.1
  tags:
    - name: "Default"
    - name: "Customer"

defaultContentType: application/json

channels:
  CustomersChannel:
    address: "customers"
    messages:
      CustomerDeletedEventMessage:
        $ref: '#/components/messages/CustomerDeletedEventMessage'
      CustomerEventMessage:
        $ref: '#/components/messages/CustomerEventMessage'

operations:
  onCustomerEvent:
    action: send
    tags:
      - name: Customer
    channel:
      $ref: '#/channels/CustomersChannel'
  onCustomerDeletedEvent:
    action: send
    tags:
      - name: Customer
    channel:
      $ref: '#/channels/CustomersChannel'

components:
  messages:
    CustomerEventMessage:
      name: CustomerEventMessage
      title: ""
      summary: ""
      traits:
        - $ref: '#/components/messageTraits/CommonHeaders'
      payload:
        schemaFormat: application/vnd.apache.avro+json;version=1.9.0
        schema:
          $ref: "avro/CustomerEvent.avsc"
    CustomerDeletedEventMessage:
      name: CustomerDeletedEventMessage
      title: ""
      summary: ""
      traits:
        - $ref: '#/components/messageTraits/CommonHeaders'
      payload:
        schemaFormat: application/vnd.apache.avro+json;version=1.9.0
        schema:
          $ref: "avro/CustomerDeletedEvent.avsc"

  messageTraits:
    CommonHeaders:
      headers:
        type: object
        properties:
          kafka_messageKey:
            type: "integer"
            format: "int64"
            description: This header value will be populated automatically at runtime
            x-runtime-expression: $message.payload#/id
          # CloudEvents Attributes
          ce-id:
            type: string
            description: Unique identifier for the event
            x-runtime-expression: $message.payload#{#this.id}
          ce-source:
            type: string
            description: URI identifying the context where event happened
            x-runtime-expression: $message.payload#{"Customer"}
          ce-specversion:
            type: string
            description: CloudEvents specification version
            x-runtime-expression: $message.payload#{"1.0"}
          ce-type:
            type: string
            description: Event type
            x-runtime-expression: $message.payload#{#this.getClass().getSimpleName()}
          ce-time:
            type: string
            description: Timestamp of when the event happened
            x-runtime-expression: $message.payload#{T(java.time.Instant).now().toString()}
```

Because `includeKafkaCommonHeaders` and `includeCloudEventsHeaders` are enabled in `ZDLToAsyncAPIPlugin`, every message carries a Kafka message key and CloudEvents headers, populated at runtime from the payload with `x-runtime-expression`:

**Kafka key and CloudEvents headers in asyncapi.yml** - `examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml` (lines 58-88), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/public/apis/asyncapi.yml#L58-L88)

```yaml
  messageTraits:
    CommonHeaders:
      headers:
        type: object
        properties:
          kafka_messageKey:
            type: "integer"
            format: "int64"
            description: This header value will be populated automatically at runtime
            x-runtime-expression: $message.payload#/id
          # CloudEvents Attributes
          ce-id:
            type: string
            description: Unique identifier for the event
            x-runtime-expression: $message.payload#{#this.id}
          ce-source:
            type: string
            description: URI identifying the context where event happened
            x-runtime-expression: $message.payload#{"Customer"}
          ce-specversion:
            type: string
            description: CloudEvents specification version
            x-runtime-expression: $message.payload#{"1.0"}
          ce-type:
            type: string
            description: Event type
            x-runtime-expression: $message.payload#{#this.getClass().getSimpleName()}
          ce-time:
            type: string
            description: Timestamp of when the event happened
            x-runtime-expression: $message.payload#{T(java.time.Instant).now().toString()}
```

## Transactional Outbox with Spring Modulith Events

Then you can configure ZenWave SDK Maven Plugin to generate all required DTOs and the `EventProducer` we saw before referenced in your `CustomerServiceImpl.java`. Setting `transactionalOutbox` to `modulith` makes the generated producer use the Spring Modulith Event Publication Registry as the transactional outbox:

**ZenWave SDK Maven Plugin (AsyncAPIGenerator) configured with transactionalOutbox modulith** - `examples/transactional-outbox-modulith-jpa/pom.xml` (lines 421-462), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/pom.xml#L421-L462)

```xml
            <plugin>
                <groupId>io.zenwave360.sdk</groupId>
                <artifactId>zenwave-sdk-maven-plugin</artifactId>
                <version>${zenwave.version}</version>
                <configuration>
                    <inputSpec>${asyncapi.inputSpec}</inputSpec>
                    <skip>false</skip>
                    <addCompileSourceRoot>true</addCompileSourceRoot>
                    <addTestCompileSourceRoot>true</addTestCompileSourceRoot>
                    <!-- <authentication>-->
                    <!--     <authentication><key>API_KEY</key><value>XXX</value></authentication> -->
                    <!-- </authentication>-->
                </configuration>
                <executions>
                    <execution>
                        <id>generate-asyncapi</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <generatorName>AsyncAPIGenerator</generatorName>
                            <configOptions>
                                <role>provider</role>
                                <transactionalOutbox>modulith</transactionalOutbox>
                                <includeApplicationEventListener>true</includeApplicationEventListener>
                                <!-- <modelPackage>${asyncApiModelPackage}</modelPackage> required for json-schema, here it uses avro package -->
                                <producerApiPackage>${asyncApiProducerApiPackage}</producerApiPackage>
                                <consumerApiPackage>${asyncApiConsumerApiPackage}</consumerApiPackage>
                                <avroCompilerProperties.imports>${asyncapi.avro.imports}</avroCompilerProperties.imports>
                            </configOptions>
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>io.zenwave360.sdk.plugins</groupId>
                        <artifactId>asyncapi-generator</artifactId>
                        <version>${zenwave.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
```

Please refer to [AsyncAPI Generator](https://www.zenwave360.io/zenwave-sdk/plugins/asyncapi-generator.md) for more details about how to configure ZenWave SDK Maven Plugin.

The plugin generates `CustomerEventsProducer` and its implementation at build time, in `target/generated-sources` (not committed to git). With `transactionalOutbox modulith`, the producer does not send to Kafka directly: it publishes a `Message` through Spring's `ApplicationEventPublisher`, so Spring Modulith stores it in the outbox in the same transaction:

**DefaultCustomerEventsProducer.java (generated in target/generated-sources)**

```java
@Component("DefaultCustomerEventsProducer")
public class DefaultCustomerEventsProducer implements CustomerEventsProducer {

  protected final ApplicationEventPublisher applicationEventPublisher;

  public String onCustomerEventBindingName = "on-customer-event-out";

  public boolean onCustomerEvent(CustomerEvent payload, CustomerEventHeaders headers) {
      log.debug("Sending message (via applicationEventPublisher) to scs binding: {}", onCustomerEventBindingName);
      headers = headers != null ? headers : new CustomerEventHeaders();
      processRuntimeHeaders(payload, headers, CustomerEventHeaders._runtimeheaders);
      headers.put("spring.cloud.stream.sendto.destination", onCustomerEventBindingName);
      Message message = MessageBuilder.createMessage(wrapNullPayload(payload), new MessageHeaders(headers));
      applicationEventPublisher.publishEvent(message);
      return true;
  }

  // ... onCustomerDeletedEvent, runtime headers (Kafka key, CloudEvents) ...
}
```

Events are stored in the `event_publication` table in the same transaction as the `Customer` aggregate, and externalized to Kafka through Spring Cloud Stream by [`spring-modulith-events-scs`](https://github.com/ZenWave360/spring-modulith-events-spring-cloud-stream). The outbox itself is Spring Modulith's; this library plugs Spring Cloud Stream, with Avro payloads generated from AsyncAPI, into it. These are the dependencies:

**Avro, Spring Modulith and spring-modulith-events-scs dependencies in pom.xml** - `examples/transactional-outbox-modulith-jpa/pom.xml` (lines 121-154), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/pom.xml#L121-L154)

```xml
		<!-- avro -->
		<dependency>
			<groupId>org.apache.avro</groupId>
			<artifactId>avro</artifactId>
			<version>${avro.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-avro</artifactId>
		</dependency>
		<!-- events-scs 1.3 serializes Avro outbox events with Jackson 3 AvroMapper -->
		<dependency>
			<groupId>tools.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-avro</artifactId>
		</dependency>
		<dependency>
			<groupId>io.confluent</groupId>
			<artifactId>kafka-avro-serializer</artifactId>
			<version>5.3.0</version>
		</dependency>
		<!-- spring modulith -->
		<dependency>
			<groupId>org.springframework.modulith</groupId>
			<artifactId>spring-modulith-starter-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.modulith</groupId>
			<artifactId>spring-modulith-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>io.zenwave360.sdk</groupId>
			<artifactId>spring-modulith-events-scs</artifactId>
			<version>${zenwave-modulith-events-scs.version}</version>
		</dependency>
```

Enable event externalization and the JDBC event publication registry in `application.yml`:

**Spring Modulith events configuration in application.yml** - `examples/transactional-outbox-modulith-jpa/src/main/resources/application.yml` (lines 14-17), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/application.yml#L14-L17)

```yaml
spring:
  modulith.events.externalization.enabled: true
  modulith.events.jdbc.schema-initialization.enabled: true
  modulith.events.republish-outstanding-events-on-restart: true
```

And bind the producer to the Kafka topic with Spring Cloud Stream, using native (Avro) encoding:

**Spring Cloud Stream binding in application.yml** - `examples/transactional-outbox-modulith-jpa/src/main/resources/application.yml` (lines 51-59), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/resources/application.yml#L51-L59)

```yaml
  cloud:
    stream:
      kafka.binder.enable-observation: true
      bindings:
        on-customer-event-out:
          destination: customer.events.avro
          content-type: application/*+avro
          producer:
            use-native-encoding: true
```

`@EnableSpringCloudStreamEventExternalization` routes the stored `Message<?>` events to Spring Cloud Stream. This example also resubmits incomplete publications every 30 seconds:

`examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/config/ExternalizationConfiguration.java` (lines 12-30), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/main/java/io/zenwave360/example/config/ExternalizationConfiguration.java#L12-L30)

```java
@Configuration
@EnableSpringCloudStreamEventExternalization
@EnableScheduling
class ExternalizationConfiguration {

    private Logger log = LoggerFactory.getLogger(ExternalizationConfiguration.class);

    @Autowired
    IncompleteEventPublications incompleteEventPublications;

    @Scheduled(fixedRate = 30000)
    public void resubmitIncompletePublications() {
        incompleteEventPublications.resubmitIncompletePublications(eventPublication -> {
            // Handle resubmitted publication
            log.debug("Resubmitted publication: " + eventPublication);
            return true;
        });
    }
}
```

For a step-by-step explanation of how these pieces fit together, read [Transactional OutBox With AsyncAPI, Spring Cloud Stream and Spring Modulith](https://www.zenwave360.io/posts/TransactionalOutBoxWithAsyncAPIAndSpringModulith/).

### Outbox Integration Tests

The outbox integration tests live in `src/test/java/io/zenwave360/example/outbox/` and run against Postgres and Kafka (docker-compose or Testcontainers):

| Test                                      | What it checks                                                                                                                                               |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `CustomerOutboxIntegrationTest`           | HTTP create -> Kafka Avro record with key and CloudEvents headers -> `event_publication` completed                                                           |
| `EventSerializerRoundTripIntegrationTest` | The Avro `Message<CustomerEvent>` survives serialize/deserialize through the library's `EventSerializer`, including rows stored by previous library releases |
| `StoredEventsResubmitIntegrationTest`     | Rows in `event_publication` are marked incomplete and resubmitted: the stored JSON is read back, rebuilt as Avro and published to Kafka again                |
| `LegacyListenerIdUpgradeIntegrationTest`  | Upgrade 1.3.x -> 1.4.x: incomplete rows with the old `listener_id` are skipped until moved to the new id with the SQL from the 1.4.0 release notes           |

`examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/outbox/CustomerOutboxIntegrationTest.java` (lines 9-32), [source](https://github.com/ZenWave360/zenwave-playground/blob/v20261205/examples/transactional-outbox-modulith-jpa/src/test/java/io/zenwave360/example/outbox/CustomerOutboxIntegrationTest.java#L9-L32)

```java
/**
 * Creates a customer through the HTTP port and asserts that Spring Modulith externalizes the CustomerEvent to Kafka
 * through Spring Cloud Stream, as an Avro record with the AsyncAPI-defined headers.
 */
class CustomerOutboxIntegrationTest extends AbstractOutboxIntegrationTest {

    @Test
    void createCustomerPublishesCustomerEventToKafka() throws Exception {
        String email = uniqueEmail();
        long id = createCustomer(email);

        ConsumerRecord<Long, CustomerEvent> record = awaitCustomerEvents(email, 1).get(0);
        assertThat(record.key()).isEqualTo(id);
        assertThat(record.value().getId()).isEqualTo(id);
        assertThat(record.value().getName().toString()).isEqualTo("John Doe");
        // The Kafka header mapper rewrites CloudEvents hyphenated names (ce-type) to ce_type.
        assertThat(header(record, "ce_type")).isEqualTo("CustomerEvent");
        assertThat(header(record, "ce_source")).isEqualTo("Customer");
        assertThat(header(record, "ce_specversion")).isEqualTo("1.0");
        assertThat(header(record, "ce_id")).isEqualTo(Long.toString(id));

        awaitPublicationCompleted(email);
    }
}
```

Recorded `serialized_event` values from earlier releases are in `src/test/resources/stored-events/<version>.json` and must keep working. To check a new release of `spring-modulith-events-scs`, bump `zenwave-modulith-events-scs.version` (and/or the Spring Boot, Modulith and Cloud versions) in `pom.xml` and run `CustomerOutboxIntegrationTest`.

## Running the Customer Service

### Prerequisites

- **JDK 25+**
- **Maven 3.8+**
- **Docker & Docker Compose** - If you don't have Docker Compose installed, we recommend [Rancher Desktop](https://rancherdesktop.io/) configured with `dockerd` engine (not `containerd`), which includes both `docker` and `docker-compose` commands.
- **Your favorite IDE**

### Quick Start

Follow these steps to run the complete application:

1. **Start infrastructure services:**
   ```bash
   docker-compose up -d
   ```

2. **Run the Spring Boot application:**
   ```bash
   mvn spring-boot:run
   ```

3. **Access the API:**
   - Open [Swagger UI](http://localhost:8080/swagger-ui/index.html) in your browser
   - Use **Basic Authentication**: username `user`, password `password`

4. **Create a customer** to publish a `CustomerEvent` through the outbox:
   ```bash
   curl -X 'POST'      'http://localhost:8080/api/customers'      -H 'accept: application/json'      -H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='      -H 'Content-Type: application/json'      -d '{
     "name": "John Doe",
     "email": "me@email.com",
     "addresses": [{ "street": "Rue del Percebe 13", "city": "Aqui" }],
     "paymentMethods": [{ "type": "VISA", "cardNumber": "string" }]
   }'
   ```

5. **Read the Avro messages from Kafka:**
   ```bash
   docker-compose exec -T schema-registry bash -c "kafka-avro-console-consumer --bootstrap-server kafka:19093 --topic customer.events.avro --from-beginning --property schema.registry.url=http://schema-registry:8081"
   ```

6. **Run the tests:** `mvn clean test` for unit tests, `mvn clean verify` for unit and integration tests.

### What's Running

- **PostgreSQL** (port 5432) - Customer data and the `event_publication` table
- **Kafka** (port 9092) - Domain events messaging, topic `customer.events.avro`
- **Schema Registry** (port 8081) - Avro schemas
- **Spring Boot App** (port 8080) - REST API and business logic

Happy Coding!
