Table of Contents
- 1. Getting Started
- 2. What you will need
- 3. Solution
- 4. The Booking Flow
- 5. Writing the Application
- 6. Configure Oracle Database and Kafka
- 7. Application Packages
- 8. Entities and Repositories
- 9. Request and Message Contracts
- 10. Transactional Booking Service
- 11. Kafka Producer
- 12. Controller: Reserve and Suspend
- 13. First Consumer: Process Payment
- 14. Second Consumer: Resume and Complete
- 15. End-to-End Tests
- 16. Testing the Application
- 17. Native Tests
- 18. Try a Booking
- 19. Generate a Micronaut Application Native Executable with GraalVM
- 20. Cleanup
- 21. Next Steps
- 22. License
Oracle Sessionless Transactions with Micronaut Data and Kafka
Learn how to use Oracle sessionless transactions with Micronaut Data and Kafka.
Authors: Milenko Supic
Micronaut Version: 5.2.3
1. Getting Started
In this guide, we will create a Micronaut application written in Java.
In this guide you will build a flight-booking workflow with an HTTP controller and two Kafka consumers. The controller reserves a seat in Oracle Database, suspends its transaction, and publishes a payment request. The first consumer processes a simulated payment. The second resumes the original Oracle Database transaction and confirms the booking, or rolls back the reservation if payment is declined.
The controller and consumers exchange the encoded global transaction identifier (GTRID), rather than a JDBC connection. The payment consumer never resumes the transaction and does not need to read the uncommitted booking.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately -
Docker, for Oracle Database Free and Kafka through Micronaut Test Resources.
-
Micronaut Data 5.2.0 or later.
-
Oracle AI Database 26ai (version 23.6 or later) and a recent Oracle JDBC Thin driver exposing
startTransaction,suspendTransactionImmediately, andresumeTransaction.
Read Developing Applications with Sessionless Transactions in the Oracle AI Database Development Guide for how the feature works, and Sessionless Transactions in the Oracle AI Database JDBC Developer’s Guide for database and driver requirements.
3. Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. The Booking Flow
The following diagram illustrates the booking flow:
-
Reserve the seat —
BookingControllerReceives
POST /bookings, reserves the seat, and saves a pending booking. It suspends the Oracle Database transaction, and then publishes aPaymentRequestedmessage containing the booking ID and GTRID to thepayment-requestsKafka topic. -
Process payment —
PaymentConsumerConsumes messages from the
payment-requestsKafka topic and processes payment while the reservation transaction remains suspended. It publishes aPaymentCompletedmessage containing the payment outcome, booking ID, and the same GTRID to thepayment-resultsKafka topic. -
Complete the booking —
CompletionConsumerConsumes messages from the
payment-resultsKafka topic and resumes the original Oracle Database transaction using the GTRID. If payment is approved, it confirms the booking and commits. If payment is declined, it rolls back the reservation.
The sample runs the controller and both consumers in one application. The consumers have separate consumer groups. They can be deployed in separate applications using the same event contracts. Reservation and completion must connect to the same Oracle Database instance and use the same application database user. No connection is held by the application while payment runs, but the suspended transaction continues to hold its database locks.
| This is an Oracle Database transaction spanning workflow steps. Kafka publishing, Kafka offset commits, and the external payment are separate operations. The example demonstrates propagation and completion; it does not provide atomic delivery or exactly-once booking across these systems. |
5. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app example.micronaut.micronautguide \
--features=data-jdbc,jdbc-hikari,oracle,liquibase,kafka,serialization-jackson,validation,awaitility \
--build=maven \
--lang=java \
--test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
If you use Micronaut Launch, select Micronaut Application as application type and add data-jdbc, jdbc-hikari, oracle, liquibase, kafka, serialization-jackson, validation, and awaitility features.
| If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
5.1. Oracle Driver
Add also the Oracle Driver
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<scope>runtime</scope>
</dependency>
6. Configure Oracle Database and Kafka
Configure the default datasource for Oracle Database:
datasources.default.driver-class-name=oracle.jdbc.OracleDriver
datasources.default.db-type=oracle
datasources.default.dialect=ORACLE
datasources.default.schema-generate=NONE
6.1. Database Migration with Liquibase
We need a way to create the database schema. For that, we use Micronaut integration with Liquibase.
Add the following snippet to include the necessary dependencies:
<dependency>
<groupId>io.micronaut.liquibase</groupId>
<artifactId>micronaut-liquibase</artifactId>
<scope>compile</scope>
</dependency>
Configure the database migrations directory for Liquibase in application.properties.
liquibase.datasources.default.change-log=classpath\:db/liquibase-changelog.xml
Create the following files with the database schema creation:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.20.xsd">
<changeSet id="1" author="micronaut">
<sqlFile path="booking.sql" relativeToChangelogFile="true"/>
</changeSet>
<changeSet id="2" author="micronaut">
<sqlFile path="seed.sql" relativeToChangelogFile="true"/>
</changeSet>
</databaseChangeLog>
Create the schema that Liquibase applies. Schema generation is disabled so that application restarts preserve committed bookings:
CREATE TABLE flight_seat (
id VARCHAR2(40) PRIMARY KEY,
status VARCHAR2(20) NOT NULL CHECK (status IN ('AVAILABLE', 'HELD', 'BOOKED'))
);
CREATE SEQUENCE booking_seq START WITH 1 INCREMENT BY 1;
CREATE TABLE booking (
id NUMBER(19) PRIMARY KEY,
seat_id VARCHAR2(40) NOT NULL REFERENCES flight_seat(id),
amount NUMBER(10, 2) NOT NULL,
status VARCHAR2(20) NOT NULL CHECK (status IN ('PENDING', 'CONFIRMED')),
payment_reference VARCHAR2(80) NOT NULL
);
Create the seed data. The changelog inserts two available seats when it initializes a new database:
INSERT INTO flight_seat (id, status) VALUES ('MN123-12A', 'AVAILABLE');
INSERT INTO flight_seat (id, status) VALUES ('MN123-12B', 'AVAILABLE');
6.2. Kafka Configuration
Configure the Kafka producer and consumers:
kafka.consumers.default.auto.offset.reset=earliest
kafka.consumers.default.enable.auto.commit=false
kafka.producers.default.enable.idempotence=true
The consumers start from the earliest available offset for a new group. Automatic offset commits are disabled; each listener uses SYNC_PER_RECORD. The producer requests acknowledgments from all in-sync replicas and enables Kafka producer idempotence. That setting covers producer retries; it does not deduplicate repeated business operations.
6.3. Test Resources Configuration
Configure Micronaut Test Resources to start an Oracle Database Free image that supports sessionless transactions in the tests:
test-resources.containers.oracle.image-name=gvenzl/oracle-free
test-resources.containers.oracle.image-tag=23.26.3-slim-faststart
test-resources.containers.oracle.startup-timeout=600s
Micronaut Test Resources supplies the datasource URL, username, password, and kafka.bootstrap.servers when they are absent. The pinned Oracle Database Free image supports sessionless transactions. For your own services, set DATASOURCES_DEFAULT_URL, DATASOURCES_DEFAULT_USERNAME, DATASOURCES_DEFAULT_PASSWORD, and KAFKA_BOOTSTRAP_SERVERS; do not put credentials in source control.
Create the two topics before sending messages when using a broker without topic auto-creation:
for topic in payment-requests payment-results; do
kafka-topics.sh --bootstrap-server localhost:9092 --create --if-not-exists \
--topic "$topic" --partitions 1 --replication-factor 1
done
One replica is suitable for the local demonstration. Configure replication and minimum in-sync replicas for your deployment.
7. Application Packages
The source code is organized under example.micronaut:
-
controller: HTTP booking endpoints. -
dto: HTTP request and response models and Kafka event payloads. -
entity: persistence entities and status enums. -
repository: Micronaut Data repositories. -
service: transactional booking operations and the demonstration payment gateway. -
kafka: the producer client and the two consumers.
The end-to-end tests exercise the booking controller.
8. Entities and Repositories
Create the FlightSeat entity, which maps the flight_seat table:
package example.micronaut.entity;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
@MappedEntity("flight_seat") (1)
public record FlightSeat(
@Id (2)
String id,
SeatStatus status
) {
}
| 1 | Annotate the class with @MappedEntity to map the class to the table defined in the schema. |
| 2 | Specifies the ID of an entity |
Create the SeatStatus enum:
package example.micronaut.entity;
import io.micronaut.serde.annotation.Serdeable;
@Serdeable (1)
public enum SeatStatus {
AVAILABLE,
HELD,
BOOKED
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
SeatStatus represents an available seat, a held reservation, and a completed booking. Micronaut Data stores the enum names in the existing VARCHAR2 status column. HTTP responses expose the same names through FlightSeatView, so the enum has @Serdeable while the entity does not.
Create the Booking entity, which maps the booking table:
package example.micronaut.entity;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.MappedEntity;
import java.math.BigDecimal;
@MappedEntity("booking") (1)
public record Booking(
@Id (2)
@GeneratedValue (3)
Long id,
String seatId,
BigDecimal amount,
BookingStatus status,
String paymentReference
) {
}
| 1 | Annotate the class with @MappedEntity to map the class to the table defined in the schema. |
| 2 | Specifies the ID of an entity |
| 3 | Specifies that the property value is generated by the database and not included in inserts |
Create the BookingStatus enum:
package example.micronaut.entity;
import io.micronaut.serde.annotation.Serdeable;
@Serdeable (1)
public enum BookingStatus {
PENDING,
CONFIRMED
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
BookingStatus represents the pending and confirmed states. Micronaut Data stores the enum names in the existing VARCHAR2 status column, and the HTTP response serializes them as PENDING or CONFIRMED. The enum is serializable because it appears in BookingView; the persistence entity still has no serialization annotation.
The HTTP endpoints return DTOs instead of persistence entities. Create FlightSeatView to represent a seat:
package example.micronaut.dto;
import example.micronaut.entity.SeatStatus;
import io.micronaut.serde.annotation.Serdeable;
@Serdeable (1)
public record FlightSeatView(String id, SeatStatus status) {
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
Create BookingView to represent a booking:
package example.micronaut.dto;
import example.micronaut.entity.BookingStatus;
import io.micronaut.serde.annotation.Serdeable;
import java.math.BigDecimal;
@Serdeable (1)
public record BookingView(Long id, String seatId, BigDecimal amount, BookingStatus status, String paymentReference) {
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
Create a repository interface for seats. Micronaut Data implements the interface at compilation time:
package example.micronaut.repository;
import example.micronaut.dto.FlightSeatView;
import example.micronaut.entity.FlightSeat;
import example.micronaut.entity.SeatStatus;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;
import java.util.Optional;
@JdbcRepository(dialect = Dialect.ORACLE) (1)
public interface FlightSeatRepository extends CrudRepository<FlightSeat, String> { (2)
Optional<FlightSeat> findByIdAndStatusForUpdate(String id, SeatStatus status);
Optional<FlightSeat> findByIdAndStatus(String id, SeatStatus status);
Optional<FlightSeatView> queryById(String id); (3)
}
| 1 | @JdbcRepository with a specific dialect. |
| 2 | By extending CrudRepository you enable automatic generation of CRUD (Create, Read, Update, Delete) operations. |
| 3 | Micronaut Data supports reflection-free Data Transfer Object (DTO) projections if the return type is annotated with @Introspected. |
The derived findByIdAndStatusForUpdate method lets Micronaut Data generate a locking read for the Oracle Database dialect that returns the seat only when it is AVAILABLE. The service persists the new status with the standard update method while holding this lock. During completion, findByIdAndStatus retrieves only a seat whose status is HELD. Oracle Database holds the lock until the original transaction commits or rolls back, including while it is suspended. Another reservation for the same seat can wait on that lock. A normal read still sees the previously committed AVAILABLE value; it cannot tell you whether a suspended reservation holds the seat.
Create a repository interface for bookings:
package example.micronaut.repository;
import example.micronaut.dto.BookingView;
import example.micronaut.entity.Booking;
import example.micronaut.entity.BookingStatus;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;
import java.util.Optional;
@JdbcRepository(dialect = Dialect.ORACLE) (1)
public interface BookingRepository extends CrudRepository<Booking, Long> { (2)
Optional<Booking> findByIdAndStatus(Long id, BookingStatus status);
Optional<BookingView> queryById(Long id); (3)
}
| 1 | @JdbcRepository with a specific dialect. |
| 2 | By extending CrudRepository you enable automatic generation of CRUD (Create, Read, Update, Delete) operations. |
| 3 | Micronaut Data supports reflection-free Data Transfer Object (DTO) projections if the return type is annotated with @Introspected. |
The Java FlightSeat and Booking entities are records, which Micronaut Data JDBC supports; the Groovy, Kotlin, and Python variants use mutable entities. The Java service creates new record values with the updated status. None of the persistence entities has serialization annotations. The booking ID uses @GeneratedValue with its default settings. For Oracle Database, Micronaut Data selects sequence generation and derives the sequence name from the table name plus _seq, so Liquibase creates booking_seq for the booking table. A new booking has no assigned ID; the inherited save method inserts it and returns the entity with its generated ID. Sequence values can have gaps after rollback. During completion, the derived findByIdAndStatus method retrieves only a booking that is still PENDING. Changes to seats and bookings use the inherited update method. The queryById methods return the FlightSeatView and BookingView DTOs directly, so Micronaut Data selects only their properties and the controller does not map entities. Both repositories let Micronaut Data generate their SQL.
9. Request and Message Contracts
Create BookingRequest to bind the body of the HTTP booking request:
package example.micronaut.dto;
import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
@Serdeable (1)
public record BookingRequest(
@NotBlank String seatId, (2)
@NotBlank @Pattern(regexp = "demo-approve|demo-decline") String paymentToken
) {
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
| 2 | Use jakarta.validation.constraints Constraints to ensure the data matches your expectations. |
Create the PaymentRequested event, which the controller publishes to request a payment:
package example.micronaut.dto;
import io.micronaut.serde.annotation.Serdeable;
import java.math.BigDecimal;
@Serdeable (1)
public record PaymentRequested(
Long bookingId,
String transactionId,
BigDecimal amount,
String paymentToken
) {
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
Create the PaymentCompleted event, which carries the payment outcome:
package example.micronaut.dto;
import io.micronaut.serde.annotation.Serdeable;
@Serdeable (1)
public record PaymentCompleted(
Long bookingId,
String transactionId,
boolean approved,
String paymentReference
) {
}
| 1 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
The controller passes only seatId to the booking service and uses the payment token from the HTTP request when constructing the payment message. Kafka messages contain only the dedicated PaymentRequested and PaymentCompleted DTOs. Persistence entities are never sent to Kafka. All events use the database-generated booking ID as their Kafka key. The controller gets this ID from the saved booking before constructing the payment request. The payment request carries the server-selected price because the pending booking is not visible outside its suspended transaction.
Micronaut’s propagation API returns the Oracle Database GTRID as a string encoded by OracleSessionlessTransactionIdCodec. Include this string in the transactionId field of the Kafka messages so the final consumer can resume the transaction. You can customize the codec, but the receiving application must be able to decode the transaction IDs sent by the producing application.
Treat the encoded GTRID as sensitive transaction-control data. Restrict access to these topics, use authenticated, encrypted connections outside local development, and avoid logging it. Do not send card details in Kafka messages; the sample uses only demonstration tokens.
10. Transactional Booking Service
Create an exception to signal a declined payment:
package example.micronaut.service;
public class PaymentDeclinedException extends RuntimeException {
public PaymentDeclinedException() {
super("Payment declined; roll back the seat reservation");
}
}
Create BookingService. It reserves a seat in a suspended transaction and later resumes that transaction to confirm or roll back the booking:
package example.micronaut.service;
import example.micronaut.dto.PaymentCompleted;
import example.micronaut.entity.Booking;
import example.micronaut.entity.BookingStatus;
import example.micronaut.entity.FlightSeat;
import example.micronaut.entity.SeatStatus;
import example.micronaut.repository.BookingRepository;
import example.micronaut.repository.FlightSeatRepository;
import io.micronaut.transaction.annotation.OracleTransactional;
import jakarta.inject.Singleton;
import java.math.BigDecimal;
import static io.micronaut.transaction.annotation.OracleTransactional.Sessionless.REQUIRES_SUSPENDED;
import static io.micronaut.transaction.annotation.OracleTransactional.Sessionless.SUSPEND;
@Singleton (9)
public class BookingService {
private final FlightSeatRepository flightSeatRepository;
private final BookingRepository bookingRepository;
public BookingService(FlightSeatRepository flightSeatRepository, BookingRepository bookingRepository) {
this.flightSeatRepository = flightSeatRepository;
this.bookingRepository = bookingRepository;
}
@OracleTransactional(sessionless = SUSPEND, timeout = 300) (1)
public Booking reserve(String seatId) {
FlightSeat seat = flightSeatRepository.findByIdAndStatusForUpdate(seatId, SeatStatus.AVAILABLE).orElseThrow(); (2)
flightSeatRepository.update(new FlightSeat(seat.id(), SeatStatus.HELD));
BigDecimal amount = new BigDecimal("199.00");
return bookingRepository.save(new Booking(null, seatId, amount, BookingStatus.PENDING, "NONE")); (3)
}
@OracleTransactional(sessionless = REQUIRES_SUSPENDED) (4)
public void complete(PaymentCompleted result) {
Booking booking = bookingRepository.findByIdAndStatus(result.bookingId(), BookingStatus.PENDING).orElseThrow(); (5)
if (!result.approved()) {
throw new PaymentDeclinedException(); (6)
}
FlightSeat seat = flightSeatRepository.findByIdAndStatus(booking.seatId(), SeatStatus.HELD).orElseThrow(); (7)
flightSeatRepository.update(new FlightSeat(seat.id(), SeatStatus.BOOKED));
bookingRepository.update(new Booking(booking.id(), booking.seatId(), booking.amount(),
BookingStatus.CONFIRMED, result.paymentReference()));
} (8)
}
| 1 | Start an Oracle Database sessionless transaction with a five-minute suspension timeout. Oracle Database cancels a transaction that remains suspended past its timeout. |
| 2 | Lock the seat with the generated findByIdAndStatusForUpdate query, which returns the seat only when it is AVAILABLE. Change its status to HELD and call update; create the pending booking with save. A competing reservation waits for the lock, and Oracle Database then re-evaluates the status condition against the latest committed row, preventing two bookings of the same seat. If no available seat is found, orElseThrow throws an exception and rolls back the transaction. |
| 3 | save returns the booking with its database-generated ID. After the intercepted method returns, Micronaut suspends the transaction instead of committing it. The generated ID and price can be published, but the database writes are still uncommitted. |
| 4 | Resume the transaction whose GTRID is in the active propagation scope. |
| 5 | This derived finder runs inside the resumed transaction and returns only the pending booking written by the controller. |
| 6 | A runtime exception rolls back the original transaction, undoing both the seat reservation and the pending booking. |
| 7 | Find the seat only when its status is HELD; if either derived finder returns no row, the operation fails and the suspended transaction is not committed. |
| 8 | Update the seat and persist the confirmed booking through the standard repository update methods. A normal return commits both changes together. Micronaut clears the GTRID from the propagation state after completion. |
| 9 | Use jakarta.inject.Singleton to designate a class as a singleton. |
These methods are top-level transaction boundaries on an injected bean. Do not call them inside another active transaction or through self-invocation. The sessionless modes require the default REQUIRED propagation and cannot be combined with @OracleTransactional.Recoverable.
11. Kafka Producer
Create an interface to send messages to Kafka. The Micronaut framework implements the interface at compilation time:
package example.micronaut.kafka;
import example.micronaut.dto.PaymentCompleted;
import example.micronaut.dto.PaymentRequested;
import io.micronaut.configuration.kafka.annotation.KafkaClient;
import io.micronaut.configuration.kafka.annotation.KafkaKey;
import io.micronaut.configuration.kafka.annotation.Topic;
import org.apache.kafka.clients.producer.RecordMetadata;
@KafkaClient(acks = KafkaClient.Acknowledge.ALL) (1)
public interface BookingClient {
@Topic("payment-requests") (2)
RecordMetadata requestPayment(@KafkaKey Long bookingId, PaymentRequested request); (3)
@Topic("payment-results")
RecordMetadata paymentCompleted(@KafkaKey Long bookingId, PaymentCompleted result);
}
| 1 | The @KafkaClient annotation is used to designate this interface as a client |
| 2 | The @Topic annotation indicates which topics the @KafkaClient should be published to. |
| 3 | The Kafka key can be specified by providing a parameter annotated with @KafkaKey. If no such parameter is specified the record is sent with a null key. |
Returning RecordMetadata makes each producer method synchronous: it waits for a Kafka acknowledgment before returning. The controller waits for its payment request to be acknowledged before returning 202 Accepted. The payment consumer waits for its result publication before its input offset is committed. There is still a crash window between suspending the Oracle Database transaction and receiving a Kafka acknowledgment.
12. Controller: Reserve and Suspend
Create BookingController to reserve seats and to expose bookings and seats over HTTP:
package example.micronaut.controller;
import example.micronaut.dto.BookingRequest;
import example.micronaut.dto.BookingView;
import example.micronaut.dto.FlightSeatView;
import example.micronaut.dto.PaymentRequested;
import example.micronaut.entity.Booking;
import example.micronaut.kafka.BookingClient;
import example.micronaut.repository.BookingRepository;
import example.micronaut.repository.FlightSeatRepository;
import example.micronaut.service.BookingService;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;
import io.micronaut.serde.annotation.Serdeable;
import io.micronaut.transaction.jdbc.oracle.OracleSessionlessTransactionPropagationOperations;
import jakarta.validation.Valid;
import java.util.Optional;
@Controller("/bookings") (1)
@ExecuteOn(TaskExecutors.BLOCKING) (2)
public class BookingController {
private final BookingClient bookingClient;
private final BookingService bookingService;
private final OracleSessionlessTransactionPropagationOperations propagation;
private final BookingRepository bookingRepository;
private final FlightSeatRepository flightSeatRepository;
public BookingController(BookingClient bookingClient,
BookingService bookingService,
OracleSessionlessTransactionPropagationOperations propagation,
BookingRepository bookingRepository,
FlightSeatRepository flightSeatRepository) {
this.bookingClient = bookingClient;
this.bookingService = bookingService;
this.propagation = propagation;
this.bookingRepository = bookingRepository;
this.flightSeatRepository = flightSeatRepository;
}
@Serdeable (10)
public record AcceptedBooking(Long bookingId) {
}
@Post (3)
public HttpResponse<AcceptedBooking> book(@Body @Valid BookingRequest request) {
PaymentRequested payment = propagation.withPropagation(() -> { (4)
Booking booking = bookingService.reserve(request.seatId()); (5)
String transactionId = propagation.currentTransactionId().orElseThrow(); (6)
return new PaymentRequested(booking.id(), transactionId, booking.amount(), request.paymentToken());
});
bookingClient.requestPayment(payment.bookingId(), payment); (7)
return HttpResponse.<AcceptedBooking>accepted().body(new AcceptedBooking(payment.bookingId()));
}
@Get("/{id}") (8)
public Optional<BookingView> find(Long id) {
return bookingRepository.queryById(id);
}
@Get("/seats/{id}") (9)
public Optional<FlightSeatView> seat(String id) {
return flightSeatRepository.queryById(id);
}
}
| 1 | The class is defined as a controller with the @Controller annotation mapped to the path /bookings. |
| 2 | It is critical that any blocking I/O operations (such as fetching the data from the database) are offloaded to a separate thread pool that does not block the Event loop. |
| 3 | The @Post annotation maps the book method to an HTTP POST request on /bookings. |
| 4 | Create an empty lexical Oracle Database propagation scope for the incoming HTTP booking request. |
| 5 | Call the injected transactional service. It saves the booking and returns the entity with its generated ID and price. Its interceptor suspends the Oracle Database transaction before returning to the controller. |
| 6 | Obtain the encoded GTRID after suspension, while the propagation scope is still active. |
| 7 | Publish the payment request after the transaction has been suspended. The event carries the GTRID even though the lexical scope has ended. |
| 8 | The @Get annotation maps the find method to an HTTP GET request on /bookings/{id}. |
| 9 | The @Get annotation maps the seat method to an HTTP GET request on /bookings/seats/{id}. |
| 10 | Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized. |
The controller returns 202 Accepted with a booking ID after Kafka acknowledges the payment request. Reservation has already run and the Oracle Database transaction is suspended, but payment and booking completion are asynchronous. Blocking Kafka sends and JDBC work run on the blocking executor. The controller is an HTTP entry point; it does not listen to a Kafka topic.
Do not publish the payment request from inside the SUSPEND method: a consumer could receive it before Oracle Database has suspended the transaction. A lexical propagation scope is not transported automatically across Kafka or asynchronous threads.
13. First Consumer: Process Payment
Create a demonstration payment gateway:
package example.micronaut.service;
import example.micronaut.dto.PaymentRequested;
import jakarta.inject.Singleton;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Singleton (1)
public class DemoPaymentGateway {
private final Map<Long, Decision> decisions = new ConcurrentHashMap<>();
public record Decision(boolean approved, String reference) {
}
public Decision pay(PaymentRequested request) {
return decisions.computeIfAbsent(request.bookingId(), id -> {
boolean approved = "demo-approve".equals(request.paymentToken());
return new Decision(approved, approved ? "demo-" + id : "DECLINED");
});
}
}
| 1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
The gateway simulates an approval for demo-approve and a decline for demo-decline. Its in-memory map makes repeated payments with the same booking ID return the same result during one process lifetime. Replace this with a payment provider that accepts a durable idempotency key; the demonstration map does not survive restarts.
Create PaymentConsumer. It listens to the payment-requests topic, processes the payment, and publishes the result:
package example.micronaut.kafka;
import example.micronaut.dto.PaymentCompleted;
import example.micronaut.dto.PaymentRequested;
import example.micronaut.service.DemoPaymentGateway;
import io.micronaut.configuration.kafka.annotation.KafkaListener;
import io.micronaut.configuration.kafka.annotation.OffsetStrategy;
import io.micronaut.configuration.kafka.annotation.Topic;
@KafkaListener(groupId = "payment-processing", offsetStrategy = OffsetStrategy.SYNC_PER_RECORD) (1)
public class PaymentConsumer {
private final DemoPaymentGateway demoPaymentGateway;
private final BookingClient bookingClient;
public PaymentConsumer(DemoPaymentGateway demoPaymentGateway, BookingClient bookingClient) {
this.demoPaymentGateway = demoPaymentGateway;
this.bookingClient = bookingClient;
}
@Topic("payment-requests") (2)
public void pay(PaymentRequested request) {
DemoPaymentGateway.Decision decision = demoPaymentGateway.pay(request); (3)
bookingClient.paymentCompleted(request.bookingId(), new PaymentCompleted(
request.bookingId(), request.transactionId(), decision.approved(), decision.reference())); (4)
}
}
| 1 | Mark the class with @KafkaListener to register it as a consumer. Its group ID identifies the consumer group, and its offset strategy controls when consumed offsets are committed. |
| 2 | The @Topic annotation is again used to indicate which topic(s) to subscribe to. |
| 3 | Process payment without entering an Oracle Database transaction or querying the pending booking. |
| 4 | Publish the result with the exact GTRID received in the payment request. |
14. Second Consumer: Resume and Complete
Create CompletionConsumer. It listens to the payment-results topic and completes the booking:
package example.micronaut.kafka;
import example.micronaut.dto.PaymentCompleted;
import example.micronaut.entity.BookingStatus;
import example.micronaut.repository.BookingRepository;
import example.micronaut.service.BookingService;
import example.micronaut.service.PaymentDeclinedException;
import io.micronaut.configuration.kafka.annotation.KafkaListener;
import io.micronaut.configuration.kafka.annotation.OffsetStrategy;
import io.micronaut.configuration.kafka.annotation.Topic;
import io.micronaut.transaction.jdbc.oracle.OracleSessionlessTransactionPropagationOperations;
@KafkaListener(groupId = "booking-completion", offsetStrategy = OffsetStrategy.SYNC_PER_RECORD) (1)
public class CompletionConsumer {
private final BookingService bookingService;
private final BookingRepository bookingRepository;
private final OracleSessionlessTransactionPropagationOperations propagation;
public CompletionConsumer(BookingService bookingService, BookingRepository bookingRepository,
OracleSessionlessTransactionPropagationOperations propagation) {
this.bookingService = bookingService;
this.bookingRepository = bookingRepository;
this.propagation = propagation;
}
@Topic("payment-results") (2)
public void complete(PaymentCompleted result) {
if (bookingRepository.findById(result.bookingId()).filter(b -> b.status() == BookingStatus.CONFIRMED).isPresent()) {
return; (3)
}
try {
propagation.withPropagation(result.transactionId(), () -> { (4)
bookingService.complete(result); (5)
return null;
});
} catch (PaymentDeclinedException expected) { (6)
// The transactional interceptor has already rolled back the reservation.
}
}
}
| 1 | Mark the class with @KafkaListener to register it as a consumer. Its group ID identifies the consumer group, and its offset strategy controls when consumed offsets are committed. |
| 2 | The @Topic annotation is again used to indicate which topic(s) to subscribe to. |
| 3 | Recognize an already committed confirmation before attempting to resume its completed GTRID. This handles sequential duplicates of a successful result; it is not a complete deduplication mechanism. |
| 4 | Import the encoded GTRID into a fresh propagation scope on the consumer thread. |
| 5 | Resume the original transaction and complete the booking through the injected service. |
| 6 | Catch the expected decline only outside the transactional service, after rollback. Catching it inside that method would allow the reservation to commit. |
A declined booking leaves no booking row: the original insert was rolled back. An absent booking can also mean it is pending, has expired, or was never started. A production workflow needs a separate durable status record to distinguish those outcomes and recognize duplicate declines.
15. End-to-End Tests
Create an end-to-end test that books seats through the HTTP API. Liquibase seeds the two demonstration seats only once per database, and each test books one of them. Test Resources can reuse the same database, for example when native tests run after the JVM tests, so each test cleans up after itself through the repositories:
package example.micronaut.controller;
import example.micronaut.dto.BookingRequest;
import example.micronaut.dto.BookingView;
import example.micronaut.dto.FlightSeatView;
import example.micronaut.entity.BookingStatus;
import example.micronaut.entity.FlightSeat;
import example.micronaut.entity.SeatStatus;
import example.micronaut.repository.BookingRepository;
import example.micronaut.repository.FlightSeatRepository;
import io.micronaut.context.annotation.Property;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.time.Duration;
import java.util.Optional;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@MicronautTest(transactional = false) (1)
@Property(name = "micronaut.test.resources.scope", value = "booking-controller-e2e") (2)
@Property(name = "micronaut.http.client.read-timeout", value = "30s")
@Timeout(120)
class KafkaBookingTest {
@Inject @Client("/") HttpClient httpClient;
@Inject BookingRepository bookingRepository;
@Inject FlightSeatRepository flightSeatRepository;
@AfterEach (3)
void resetSeats() {
bookingRepository.deleteAll();
flightSeatRepository.update(new FlightSeat("MN123-12A", SeatStatus.AVAILABLE));
flightSeatRepository.update(new FlightSeat("MN123-12B", SeatStatus.AVAILABLE));
}
@Test
void approvedPaymentConfirmsTheBooking() {
String seatId = "MN123-12A";
assertEquals(SeatStatus.AVAILABLE, findSeat(seatId).status());
Long bookingId = book(seatId, "demo-approve");
awaitConfirmed(bookingId, seatId);
}
@Test
void declinedPaymentRollsBackAndAllowsTheSameSeatToBeBookedAgain() {
String seatId = "MN123-12B";
assertEquals(SeatStatus.AVAILABLE, findSeat(seatId).status());
Long declinedBookingId = book(seatId, "demo-decline"); (4)
Long approvedBookingId = book(seatId, "demo-approve"); (5)
assertNotEquals(declinedBookingId, approvedBookingId);
awaitConfirmed(approvedBookingId, seatId); (6)
assertTrue(findBooking(declinedBookingId).isEmpty()); (7)
}
private Long book(String seatId, String paymentToken) {
var response = httpClient.toBlocking().exchange(
HttpRequest.POST("/bookings", new BookingRequest(seatId, paymentToken)),
BookingController.AcceptedBooking.class);
assertEquals(HttpStatus.ACCEPTED, response.getStatus());
Long bookingId = response.body().bookingId();
assertNotNull(bookingId);
assertTrue(bookingId > 0);
return bookingId;
}
private void awaitConfirmed(Long bookingId, String seatId) {
await().atMost(Duration.ofSeconds(60)).untilAsserted(() -> {
Optional<BookingView> booking = findBooking(bookingId);
assertTrue(booking.isPresent(), "Booking has not committed yet");
BookingView view = booking.orElseThrow();
assertEquals(bookingId, view.id());
assertEquals(seatId, view.seatId());
assertEquals(BookingStatus.CONFIRMED, view.status());
assertEquals("demo-" + bookingId, view.paymentReference());
assertEquals(SeatStatus.BOOKED, findSeat(seatId).status());
});
}
private Optional<BookingView> findBooking(Long bookingId) {
try {
return Optional.of(httpClient.toBlocking().retrieve("/bookings/" + bookingId, BookingView.class));
} catch (HttpClientResponseException e) {
if (e.getStatus() == HttpStatus.NOT_FOUND) {
return Optional.empty();
}
throw e;
}
}
private FlightSeatView findSeat(String seatId) {
return httpClient.toBlocking().retrieve("/bookings/seats/" + seatId, FlightSeatView.class);
}
}
| 1 | Configure the test with @MicronautTest so Micronaut initializes the application context and embedded server. Tests are transactional by default, and each test transaction rolls back when the test finishes. Set transactional to false when the test must observe committed database changes. |
| 2 | Annotate the class with @Property to supply configuration to the test. |
| 3 | After each test, delete the bookings with BookingRepository and make both demonstration seats AVAILABLE again with FlightSeatRepository. |
| 4 | Submit a declined booking for the seeded MN123-12B seat. |
| 5 | Submit an approved booking for the exact same seat. This request must acquire the lock held by the first reservation, so it can return only after that lock is released. |
| 6 | Poll until the replacement booking is CONFIRMED and its seat is BOOKED. |
| 7 | Verify the declined booking lookup returns 404, showing that its pending insert was rolled back. |
The test submits booking requests through the HTTP API and polls the booking and seat endpoints to verify the outcome. The approval scenario books the seeded MN123-12A seat, then polls until the booking is CONFIRMED with a payment reference and the seat is BOOKED.
An absent booking or an AVAILABLE seat alone would be a false positive: those are also visible while a reservation is suspended. Successfully booking the same seat again and confirming that the declined booking remains absent verify rollback through the public API. The tests use a 30-second HTTP request timeout and a 60-second polling deadline, both shorter than the five-minute Oracle Database suspension timeout, so transaction expiry cannot make this scenario pass.
The test has no surrounding transaction and uses a dedicated Micronaut Test Resources scope, with its own Oracle Database and Kafka containers. Docker is required; the build stops the disposable Test Resources services after the tests.
16. Testing the Application
To run the tests:
./mvnw test
17. Native Tests
The Maven plugin for GraalVM Native Image building allows you to run native tests.
This plugin supports running tests on the JUnit Platform as native images. This means that tests will be compiled and executed as native code.
First, add the following profile to pom.xml:
<profile>
<id>native</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
Then, to execute the native tests, execute:
./mvnw -Pnative test
INFO: A test may be disabled within a GraalVM native image via the @DisabledInNativeImage annotation.
18. Try a Booking
Start the application with ./mvnw mn:run.
Test Resources starts local Oracle Database and Kafka containers if external connection properties are absent.
Liquibase inserts MN123-12A and MN123-12B when it initializes a new database. These rows are available for the booking requests below; after a successful booking, that seat remains BOOKED across application restarts.
curl -i -X POST http://localhost:8080/bookings \
-H 'Content-Type: application/json' \
-d '{"seatId":"MN123-12A","paymentToken":"demo-approve"}'
Copy bookingId from the response and poll:
curl http://localhost:8080/bookings/BOOKING_ID
curl http://localhost:8080/bookings/seats/MN123-12A
Before completion, the booking lookup returns 404; after completion, it returns a booking with status: CONFIRMED and the seat is BOOKED.
Try MN123-12B with demo-decline. After payment processing and rollback, no booking is visible and the seat remains AVAILABLE. The sample has no separate rejection-status endpoint. Use a different available seat for later successful requests, or recreate the disposable database to reset the demonstration.
19. Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.
Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
19.1. GraalVM Installation
sdk install java 25.4.4+1-graal
For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 25.4.4.1+1-graalce
19.2. Native Executable Generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-image
The native executable is created in the target directory and can be run with target/micronautguide.
It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.11.5</version>
<configuration>
(1)
<imageName>mn-graalvm-application</imageName>
<buildArgs>
(2)
<buildArg>-Ob</buildArg>
</buildArgs>
</configuration>
</plugin>
| 1 | The native executable name will now be mn-graalvm-application. |
| 2 | It is possible to pass extra build arguments to native-image. For example, -Ob enables the quick build mode. |
19.3. Liquibase Reflection Metadata
Liquibase applies the attributes of the changelog’s sqlFile changes through reflection. Register those classes for GraalVM Native Image:
{
"reflection": [
{
"type": "liquibase.change.core.SQLFileChange",
"allPublicConstructors": true,
"allPublicMethods": true
},
{
"type": "liquibase.change.AbstractSQLChange",
"allPublicMethods": true
}
]
}
Without this file, the native executable and the native tests fail at startup with a MissingReflectionRegistrationError for liquibase.change.core.SQLFileChange.
Micronaut Test Resources does not start containers for the native executable. Set DATASOURCES_DEFAULT_URL, DATASOURCES_DEFAULT_USERNAME, DATASOURCES_DEFAULT_PASSWORD, and KAFKA_BOOTSTRAP_SERVERS before you run it.
20. Cleanup
Stop the application and its Test Resources services.
Use ./mvnw mn:stop-testresources-service to stop the Maven Test Resources service.
The containers are disposable; no cloud resources are provisioned by this guide. Remove demonstration topics only from a broker dedicated to this example.
21. Next Steps
Read the Micronaut Data sessionless transaction documentation, the Micronaut Kafka guide, and the Oracle AI Database documentation on sessionless transactions: Developing Applications with Sessionless Transactions and JDBC Sessionless Transactions.
22. License
| All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |