CAP has two runtimes with the same CDS model: Node.js (page 04) and Java on Spring Boot. This page builds the Order Approval Portal's custom logic a second time in Java, for a team that prefers Spring Boot (CR5): project structure, Maven and the cds-maven-plugin, the generated accessor interfaces, event handlers with @ServiceName, @Before, @On and @After, the CQL query builder and CQN, the PersistenceService, actions, security, running locally and a Node.js vs Java comparison. Concepts that are the same in both runtimes (phases, transactions, actions in CDS) are explained on page 04 and only mapped here. Sources: capire (cap.cloud.sap/docs/java) and the SAP-samples cloud-cap-samples-java bookshop. Versions follow CAP Java 5 (JDK 21 minimum, Spring Boot 4.1).
Part 1 – Why CAP Java, and what this page builds
Requirements on this page
ID | Requirement | CAP Java concept | Part |
|---|---|---|---|
CR5 | The same service in Java for a team that prefers Spring Boot | CAP Java project, Maven build | 2, 3 |
CR3 (Java) | Deadline and region defaults, input checks, overdue colour |
| 5 |
CR4 (Java) | Approve / reject and the open-request counter | generated action contexts, CQN | 6, 8 |
CR7 (Java) | Only managers approve; mock users locally | CDS annotations, | 9 |
Why a Java runtime at all? Many SAP customers and partners run Java teams, Spring Boot standards, Java libraries and Java operations tooling. CAP Java lets them use the same CDS models, OData services, Fiori annotations and BTP services as Node.js projects – only the handler code is Java. For the interview: both runtimes are fully supported by SAP; the choice is about the team and ecosystem, not about features of the programming model.
Same as Node.js (explained once) | Different in Java (this page) |
|---|---|
CDS model, services, projections (pages 02, 03) | Maven project, Spring Boot application |
Phases before / on / after (page 04, Part 3) | annotated methods in a Spring bean |
CQL semantics, path expressions (page 04, Parts 5–6) | fluent Java query builder → CQN objects |
One transaction per request (page 04, Part 7) | ChangeSet context, Spring transactions |
Actions and functions in CDS (page 04, Part 8) | generated typed event contexts |
@requires / @restrict (page 07) |
|
ABAP view: CAP Java feels closer to ABAP than Node.js – static types, a compiler that breaks when the model changes, and generated structures for every entity (like DDIC types for a CDS view).
Part 2 – Creating the project and its structure
Two ways create the same layout: the CDS tools (cds init --java) or the Maven archetype. Both produce a parent POM, a db/ folder for the model and an srv/ Maven module for services and Java code.
|

Folder / file | Content |
|---|---|
db/ | the CDS domain model and CSV test data – identical to the Node.js project |
srv/*.cds | service definitions – identical; set |
srv/pom.xml | the Spring Boot module: CAP starters, protocol adapter, |
srv/src/main/java/ |
|
srv/src/main/resources/application.yaml | Spring and CAP configuration, profiles, mock users |
srv/src/gen/java/ | generated accessor interfaces after the first |
package.json |
|
- Requirements of CAP Java 5: JDK 21 or later (JDK 25 is the default for new projects), Maven 3.9.14 or later and Spring Boot 4.1. CAP Java 2 to 4 (Spring Boot 3) ran on Java 17.
Part 3 – Maven and the cds-maven-plugin
The CDS compiler is a Node.js tool. The cds-maven-plugin hides that from Java developers: during mvn install it installs Node.js and @sap/cds-dk locally, compiles the CDS model and generates Java interfaces. At runtime the application is pure Java – no Node.js.
|
|
Goal | What it does |
|---|---|
clean | removes artifacts of the previous CDS build |
install-node | downloads a local Node.js for the build (no global installation needed) |
| installs |
cds | runs CDS commands, typically |
generate | generates accessor interfaces, |
add | adds features to the project ( |
cds-services-bomis a bill of materials: import it once and leave versions off the CAP dependencies, so all modules stay compatible. Optional features come as extra modules, e.g.cds-feature-flowfor status flows (Part 8).
Part 4 – Generated accessor interfaces
Why: in Node.js an approval request is a plain JavaScript object. In Java you want compile-time safety: a typo in a field name should break the build, not production. The generate goal creates Java interfaces for every entity, structured type, action and service in the model.
Generated type (package | Purpose | Example use |
|---|---|---|
ApprovalRequests | accessor interface – getters/setters on a |
|
ApprovalRequests_ | model interface for the query builder (elements, associations) | Select.from(ApprovalRequests_.class).where(r -> r.status().eq("N")) |
ApprovalRequestsApproveContext | event context of the bound action |
|
| event context of the unbound function | ctx.setResult(n) |
| typed service interface and | @ServiceName(ManagerService_.CDS_NAME) |
|
- Accessor objects are maps, so generic code (JSON, logging) still works – the typed interface is only a view. Element names are also available as constants, e.g.
ApprovalRequests.STATUS. - Element names map to Java names:
ID→getId(), foreign keyrequest_ID→getRequestId(). Never editsrc/gen– it is overwritten on every build.
Part 5 – Event handlers: @ServiceName, @Before, @On, @After
A handler class is a Spring bean (@Component) that implements the marker interface EventHandler and names the CDS service it serves with @ServiceName. Each method annotated with @Before, @On or @After is registered for an event and entity – the same three phases as on page 04, Part 3.

Phase (Java) | Semantics (capire) | Node.js twin |
|---|---|---|
@Before | filtering, validation, preprocessing; an exception ends processing; error messages collected so far are thrown after the phase | this.before |
@On | core processing; the first handler that completes the event ( |
|
@After | only after a successful On phase; post-processing of results | this.after |
5.1 CR3 in Java – defaults, validation, overdue colour
|
Handler feature | How |
|---|---|
Typed data | declare |
Event context |
|
Several events | @Before(event = { CqnService.EVENT_CREATE, CqnService.EVENT_UPDATE }, entity = …) |
Derived registration | for actions, the event and entity can be derived from the argument types ( |
Ordering |
|
Errors |
|
- Use the generated constants (
ApprovalRequests_.CDS_NAME,RepService_.CDS_NAME) instead of strings – a renamed entity then fails at compile time. Message targets (field highlighting) are set withtarget(…)on a message, e.g..target(Books_.class, b -> b.title()), ormessageTarget(…)on aServiceException.
Part 6 – The CQL query builder and CQN
CQN (CDS Query Notation) is the object form of a CQL query – the same concept as in Node.js. In Java you build it with the fluent builder classes Select, Insert, Upsert, Update and Delete (package com.sap.cds.ql). The OData adapter also turns every incoming request into CQN, which your handler can read with ctx.getCqn() and pass on.
|
Result method | Returns |
|---|---|
| exactly one row (throws if there is none or more) |
|
|
listOf(ApprovalRequests.class) | typed list |
| Java stream |
rowCount() | affected rows (update, delete) or number of rows |
- Static style = compile-time checked lambdas on the
*_model; dynamic style = strings for generic or configurable code. Both build the same CQN. Values go in as parameters – no SQL injection through the builder. - Expands use
.columns(r -> r.notes().expand())for all elements orr.notes().expand(n -> n.text())for a nested projection;.as("alias")and.excluding(…)also work on an expand.
Part 7 – PersistenceService, other services and transactions
Every CAP Java service is a CqnService you can run(…) CQN against. Two kinds matter here:
Service | What | Use in a handler for |
|---|---|---|
| CQN → SQL for H2, SQLite, PostgreSQL or SAP HANA Cloud; no application handlers, no service-level authorization | reading and writing your own data |
Application service (e.g. generated | full Before/On/After pipeline of that service, including your handlers and checks | calling another service on purpose |
Remote service (imported S/4HANA API) | CQN → OData request via destination | CR9, → page 09 |
|
Database | Use (capire) |
|---|---|
H2 | recommended in-memory database for local development and tests |
SQLite | development and tests only |
PostgreSQL | supported, with limitations (e.g. no multitenancy / extensibility) |
SAP HANA Cloud | standard for production, schema evolution, multitenancy – → page 08 |
Transactions: as in Node.js, CAP Java runs each request (each OData changeset) in one transaction and commits or rolls back at the end; your db.run(…) calls join it automatically. For work outside requests (jobs, startup) you open your own request and ChangeSet contexts through the CdsRuntime (runtime.requestContext().run(…), runtime.changeSetContext().run(…)); Spring's @Transactional also works, because CAP Java integrates with Spring's transaction manager.
Part 8 – Actions and functions in Java (CR4)
The CDS declarations of approve(), reject(reason) and openCount() are exactly those of pages 03 and 04 – one model for both runtimes. The plugin generates one event context per operation; for bound actions the name is prefixed with the entity (ApprovalRequestsApproveContext).
|
Point | Detail |
|---|---|
Registration |
|
Instance key |
|
Parameters | typed getters on the context, e.g. |
Result |
|
Status check without code |
|
HTTP | same URLs as Node.js once |
reject(ApprovalRequestsRejectContext) is the same method with statusR: a@BeforethrowsServiceException(ErrorStatuses.BAD_REQUEST, …)whenctx.getReason()is blank (CR3), the@Onwritesreasonto the request and the decisioncomment. Put the shared logic into a private methoddecide(String id, String outcome, String reason).- Emitting
RequestDecidedand messaging in Java (MessagingService, outbox) → see CAP › 10 · Messaging & Events.
Part 9 – Security in CAP Java
Authorization is declared once in CDS – @requires: 'Manager' on ManagerService, @restrict for the region rule – and enforced by the CAP Java runtime just like in Node.js. Concepts, XSUAA vs IAS, AMS and the approuter: → see CAP › 07 · Authorization & Security. Java-specific pieces:
Topic | CAP Java |
|---|---|
Runtime dependencies |
|
Authentication mode |
|
Mock users (local) |
|
Current user in code |
|
Locale | ctx.getParameterInfo().getLocale() |
|
- Never ship mock users to production: keep them in a local Spring profile. On BTP the starter switches to real tokens automatically when XSUAA / IAS is bound.
Part 10 – Running, testing and deploying locally
|
Task | How |
|---|---|
Run |
|
Fast restart |
|
Same URLs as Node.js | set |
Tests | Spring Boot tests ( |
Build for BTP |
|
Part 11 – Node.js vs Java

Same task | Node.js | Java |
|---|---|---|
Register a before handler | this.before('CREATE', ApprovalRequests, req => …) | @Before(event = CqnService.EVENT_CREATE, entity = ApprovalRequests_.CDS_NAME) |
Change the payload | req.data.status = 'N' |
|
Read open requests | await SELECT.from(ApprovalRequests).where({ status: 'N' }) | db.run(Select.from(ApprovalRequests_.class).where(r -> r.status().eq("N"))) |
Key of a bound action |
|
|
Business error | req.reject(409, 'Already decided') | throw new ServiceException(ErrorStatuses.CONFLICT, "Already decided") |
Collect field errors | req.error(…) | ctx.getMessages().error(…) |
Current user |
|
|
Local start |
|
|
How to decide (interview answer): both runtimes implement the same programming model and are supported by SAP. Choose by team skills and the ecosystem you must integrate with. Node.js usually offers the faster inner loop and gets many new CAP plugins first; Java brings static typing, Spring and existing Java libraries and operations standards. The CDS model, the APIs and the Fiori app do not change – a migration rewrites only the handlers.
Part 12 – Interview questions
Q1. How is a CAP Java project structured, and what does the cds-maven-plugin do?
A parent POM, db/ for the CDS model, srv/ as a Spring Boot Maven module with service CDS files, Java handlers and application.yaml. The plugin installs Node.js and @sap/cds-dk for the build, runs cds build --for java (CSN, EDMX, schema) and generates Java interfaces into src/gen/java. At runtime only Java runs.
Q2. What are the generated accessor interfaces, and why use them?
Interfaces such as ApprovalRequests (getters/setters over a map, extends CdsData), ApprovalRequests_ (model for the query builder), event contexts for actions and service interfaces. They give compile-time safety: a renamed element breaks the build instead of failing at runtime, while the data stays a map.
Q3. How do you write an event handler in CAP Java?
A Spring @Component that implements EventHandler, annotated with @ServiceName(ManagerService_.CDS_NAME). Methods carry @Before, @On or @After with event and entity (generated constants), and receive the event context and/or typed data like List<ApprovalRequests> as arguments.
Q4. What is CQN, and how do you build and run a query in Java?
CQN is the object representation of a CQL query. You build it with Select, Insert, Upsert, Update, Delete – typed with lambdas on *_ models or dynamic with strings – and execute it with service.run(query), getting a Result (single, first, listOf, rowCount).
Q5. PersistenceService vs an application service – which do you call in a handler?
PersistenceService talks to the database directly – no application handlers, no service-level authorization – right for your own reads and writes. An application service (ManagerService) runs its whole handler pipeline; call it when you deliberately want its logic and checks.
Q6. How does an On handler end the event, and how do multiple On handlers interact?
An On handler completes the event with setResult(…), setCompleted() or a return value; the remaining On handlers are then skipped. If no custom handler completes it, the generic CRUD handler does. @HandlerOrder controls the order.
Q7. How do you implement a bound action in Java?
Declare it in CDS; the plugin generates ApprovalRequestsApproveContext. Write @On public ApprovalRequests approve(ApprovalRequests_ ref, ApprovalRequestsApproveContext ctx), read the instance key with CqnAnalyzer.analyze(ctx.getCqn()).targetKeys(), parameters with typed getters, and return or setResult the result.
Q8. How do you report errors in CAP Java?
Throw ServiceException with an ErrorStatuses value (e.g. CONFLICT) for fatal errors, or collect messages with ctx.getMessages().error(…); CAP throws collected errors after the Before phase (throwIfError). Warnings and success messages go to the sap-messages header.
Q9. How do you test security locally in CAP Java?
Define mock users with roles and attributes under cds.security.mock.users in a local profile of application.yaml; they are used only when no XSUAA / IAS binding exists. In code use UserInfo (getName(), hasRole()); the CDS annotations are enforced by the runtime.
Q10. Scenario: your company has a Java team but the CAP sample you found is Node.js. What changes if you port the Order Approval Portal to Java?
The db/ and srv/ CDS files, annotations, Fiori app and MTA stay. You create a CAP Java project, rewrite handlers as Spring beans (req.data → typed lists, cds.ql → query builder, req.reject → ServiceException), configure mock users in application.yaml, set @path so URLs match, and move tests to Spring Boot tests.
Q11. Scenario: after a model change the Java build fails with "cannot find symbol getRegion()". Why is this good, and what do you do?
The accessor interfaces were regenerated from the new model, and a handler still uses an element that was renamed or removed. The compiler catches it before deployment – in Node.js it would fail at runtime. Adapt the handler to the new element name (or fix the model) and rebuild; never edit src/gen.
🏠 Start Here · ◀ 04 · Node.js Logic · 06 · Fiori & Draft ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC
Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | EHS ABAP | HR ABAP | BW | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP