Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CAP / CAP Java – Spring Boot, Handlers & CQN

CAP Java – Spring Boot, Handlers & CQN

CAP · SAP BTP ·

Open the interactive lesson →
  1. Why CAP Java, and what this page builds
  2. Creating the project and its structure
  3. Maven and the cds-maven-plugin
  4. Generated accessor interfaces
  5. Event handlers: @ServiceName, @Before, @On, @After
  6. The CQL query builder and CQN
  7. PersistenceService, other services and transactions
  8. Actions and functions in Java (CR4)
  9. Security in CAP Java
  10. Running, testing and deploying locally
  11. Node.js vs Java
  12. Interview questions

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

@Before / @After handlers, Messages API

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, UserInfo, application.yaml

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)

UserInfo, mock users in application.yaml

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.

# with the CDS development kit
cds init order-approval-java --java
cd order-approval-java

# or with the Maven archetype (interactive: groupId, artifactId, package)
mvn archetype:generate -DarchetypeArtifactId="cds-services-archetype" -DarchetypeGroupId="com.sap.cds"

# add capabilities later through the plugin's add goal, for example
mvn com.sap.cds:cds-maven-plugin:add -Dfeature=TINY_SAMPLE     # small sample model
mvn com.sap.cds:cds-maven-plugin:add -Dfeature=CF              # Cloud Foundry starter
mvn com.sap.cds:cds-maven-plugin:add -Dfeature=INTEGRATION_TEST
CAP Java project tree with db, srv, generated sources and the Maven build steps: install-node and npm ci, cds build, generate, javac, spring-boot:run

Folder / file

Content

db/

the CDS domain model and CSV test data – identical to the Node.js project

srv/*.cds

service definitions – identical; set @path to keep the same URLs in both runtimes

srv/pom.xml

the Spring Boot module: CAP starters, protocol adapter, cds-maven-plugin

srv/src/main/java/

Application.java (@SpringBootApplication) and your handler classes

srv/src/main/resources/application.yaml

Spring and CAP configuration, profiles, mock users

srv/src/gen/java/

generated accessor interfaces after the first mvn compile – never edit

package.json

@sap/cds-dk version used by the build (installed with npm ci)

  • 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.

<!-- pom.xml (parent) – keep all CAP Java modules on one version -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-services-bom</artifactId>
<version>${cds.services.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<!-- srv/pom.xml – runtime dependencies -->
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-starter-spring-boot</artifactId>     <!-- CAP runtime + Spring Boot integration -->
</dependency>
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-adapter-odata-v4</artifactId>        <!-- protocol adapter: OData V4 endpoints -->
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-starter-cloudfoundry</artifactId>    <!-- XSUAA/IAS, HANA, service bindings on BTP -->
</dependency>
<!-- srv/pom.xml – build: abridged, the archetype generates the full version -->
<plugin>
<groupId>com.sap.cds</groupId>
<artifactId>cds-maven-plugin</artifactId>
<executions>
<execution><id>cds.clean</id><goals><goal>clean</goal></goals></execution>
<execution><id>cds.install-node</id><goals><goal>install-node</goal></goals></execution>
<execution><id>cds.npm-ci</id><goals><goal>npm</goal></goals>
<configuration><arguments>ci</arguments></configuration></execution>
<execution><id>cds.build</id><goals><goal>cds</goal></goals>
<configuration><commands><command>build --for java</command></commands></configuration></execution>
<execution><id>cds.generate</id><goals><goal>generate</goal></goals>
<configuration><basePackage>cds.gen</basePackage></configuration></execution>
</executions>
</plugin>

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)

npm (ci)

installs @sap/cds-dk from package.json + lock file (replaces the deprecated install-cdsdk goal)

cds

runs CDS commands, typically build --for java: CSN, EDMX, database schema

generate

generates accessor interfaces, *_ model interfaces, event contexts and service interfaces (default: JavaBeans-style getters/setters)

add

adds features to the project (-Dfeature=…)

  • cds-services-bom is 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-flow for 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 cds.gen.managerservice)

Purpose

Example use

ApprovalRequests

accessor interface – getters/setters on a Map (extends CdsData)

r.getStatus(), r.setDeadline(…), ApprovalRequests.create()

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 approve – typed parameters and result

ctx.getCqn(), ctx.setResult(…); for reject: ctx.getReason()

OpenCountContext (package cds.gen.repservice)

event context of the unbound function openCount in RepService

ctx.setResult(n)

ManagerService, ManagerService_

typed service interface and CDS_NAME constant

@ServiceName(ManagerService_.CDS_NAME)

import cds.gen.managerservice.ApprovalRequests;
import cds.gen.managerservice.Decisions;

ApprovalRequests r = ApprovalRequests.create();      // empty typed data container
r.setSalesOrder("4711");
r.setNetAmount(new BigDecimal("25000.00"));           // Decimal -> BigDecimal
r.setDeadline(LocalDate.now().plusDays(3));           // Date    -> LocalDate
String status = r.getStatus();                        // String(1) -> String
Object raw = r.get("status");                         // still a Map: CdsData extends Map<String, Object>

Decisions d = Struct.access(someMap).as(Decisions.class);   // typed view on an existing map
  • 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 key request_ID → getRequestId(). Never edit src/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.

OData adapter to ApplicationService to PersistenceService, and a handler class with @Component, @ServiceName, @Before, @On, @After methods and notes on arguments, ordering and errors

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 (setResult, setCompleted, or a return value) skips the remaining On handlers; generic CRUD runs here

this.on + next()

@After

only after a successful On phase; post-processing of results

this.after

5.1 CR3 in Java – defaults, validation, overdue colour

package com.example.orderapproval.handlers;

import cds.gen.repservice.ApprovalRequests;
import cds.gen.repservice.ApprovalRequests_;
import cds.gen.repservice.RepService_;
import com.sap.cds.services.cds.CdsCreateEventContext;
import com.sap.cds.services.cds.CqnService;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.*;
import com.sap.cds.services.messages.Messages;
import java.time.LocalDate;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
@ServiceName(RepService_.CDS_NAME)
public class RepServiceHandler implements EventHandler {

@Before(event = CqnService.EVENT_CREATE, entity = ApprovalRequests_.CDS_NAME)
public void checkInput(CdsCreateEventContext ctx, List<ApprovalRequests> requests) {
Messages messages = ctx.getMessages();
List<String> myRegions = ctx.getUserInfo().getAttributeValues("region");    // e.g. [EMEA] for mia
for (ApprovalRequests r : requests) {
if (r.getTypeCode() == null)
messages.error("Choose a request type (CRED, DISC or PRIC)");
if (r.getRegion() != null && !myRegions.contains(r.getRegion()))
messages.error("You cannot create requests for region " + r.getRegion());
}
}   // CAP calls messages.throwIfError() after the Before phase -> one error response with all messages

@Before(event = CqnService.EVENT_CREATE, entity = ApprovalRequests_.CDS_NAME)
public void setDefaults(CdsCreateEventContext ctx, List<ApprovalRequests> requests) {
List<String> myRegions = ctx.getUserInfo().getAttributeValues("region");
for (ApprovalRequests r : requests) {
r.setDeadline(LocalDate.now().plusDays(3));                  // status: CDS default #New
if (r.getRegion() == null && !myRegions.isEmpty()) r.setRegion(myRegions.get(0));
}
}

@After(event = CqnService.EVENT_READ, entity = ApprovalRequests_.CDS_NAME)
public void criticality(List<ApprovalRequests> rows) {      // virtual criticality : Integer
LocalDate today = LocalDate.now();
for (ApprovalRequests r : rows) {
boolean overdue = r.getDeadline() != null && r.getDeadline().isBefore(today);
r.setCriticality("A".equals(r.getStatus()) ? 3 : "R".equals(r.getStatus()) || overdue ? 1 : 2);
}
}
}

Handler feature

How

Typed data

declare List<ApprovalRequests> or Stream<ApprovalRequests> as argument – CAP passes the request payload (before) or the result (after)

Event context

CdsReadEventContext, CdsCreateEventContext, CdsUpdateEventContext, … – getCqn(), getMessages(), getUserInfo(), setResult(…)

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 (ApprovalRequests_ ref, ApprovalRequestsApproveContext ctx) – Part 8

Ordering

@HandlerOrder(HandlerOrder.EARLY) / HandlerOrder.LATE; overrides Spring @Order

Errors

throw new ServiceException(ErrorStatuses.CONFLICT, "…") (default status 500 if none); messages with ctx.getMessages().error/warn/success(…) – returned in sap-messages or in the error details

  • 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 with target(…) on a message, e.g. .target(Books_.class, b -> b.title()), or messageTarget(…) on a ServiceException.

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.

import static com.sap.cds.ql.CQL.*;          // optional helpers
import com.sap.cds.ql.*;

// SELECT – static (typed) style
CqnSelect open = Select.from(ApprovalRequests_.class)
.columns(r -> r.ID(), r -> r.salesOrder(), r -> r.customer().name().as("customer"))   // path = JOIN
.where(r -> r.status().eq("N").and(r.netAmount().gt(10000)))
.orderBy(r -> r.deadline().asc());
List<ApprovalRequests> rows = db.run(open).listOf(ApprovalRequests.class);

// by key, single row
ApprovalRequests one = db.run(Select.from(ApprovalRequests_.class).byId(id)).single(ApprovalRequests.class);

// SELECT – dynamic (string) style, e.g. for generic code
CqnSelect dyn = Select.from("ManagerService.ApprovalRequests").columns("ID", "status").byId(id);

// INSERT / UPSERT
db.run(Insert.into(Decisions_.class).entry(decision));
db.run(Upsert.into(Customers_.class).entry(customer));

// UPDATE – by key, or conditional (optimistic guard)
db.run(Update.entity(ApprovalRequests_.class).data(ApprovalRequests.STATUS, "A").byId(id));
long n = db.run(Update.entity(ApprovalRequests_.class).data(ApprovalRequests.STATUS, "A")
.where(r -> r.ID().eq(id).and(r.status().eq("N")))).rowCount();

// DELETE
db.run(Delete.from(Notes_.class).where(n -> n.request().ID().eq(id)));

Result method

Returns

single() / single(ApprovalRequests.class)

exactly one row (throws if there is none or more)

first() / first(ApprovalRequests.class)

Optional of the first row

listOf(ApprovalRequests.class)

typed list

stream() / streamOf(ApprovalRequests.class)

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 or r.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 run(query) does

Use in a handler for

PersistenceService (the database)

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 ManagerService)

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

@Component
@ServiceName(ManagerService_.CDS_NAME)
public class ManagerServiceHandler implements EventHandler {

private final PersistenceService db;      // the default database
private final CqnAnalyzer analyzer;       // extracts keys from CQN statements

ManagerServiceHandler(PersistenceService db, CdsModel model) {   // constructor injection by Spring
this.db = db;
this.analyzer = CqnAnalyzer.create(model);
}
// handlers in Part 8
}

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).

@Before
public void checkOpen(ApprovalRequests_ ref, ApprovalRequestsApproveContext ctx) {
ApprovalRequests r = db.run(ctx.getCqn()).first(ApprovalRequests.class)     // CQN points to the instance
.orElseThrow(() -> new ServiceException(ErrorStatuses.NOT_FOUND, "Approval request not found"));
if (!"N".equals(r.getStatus()))
throw new ServiceException(ErrorStatuses.CONFLICT, "Request is already decided");
}

@On
public ApprovalRequests approve(ApprovalRequests_ ref, ApprovalRequestsApproveContext ctx) {
String id = (String) analyzer.analyze(ctx.getCqn()).targetKeys().get(ApprovalRequests.ID);

db.run(Update.entity(ApprovalRequests_.class).data(ApprovalRequests.STATUS, "A").byId(id));

Decisions d = Decisions.create();
d.setRequestId(id);
d.setOutcome("A");                                     // createdBy = manager (managed aspect)
db.run(Insert.into(Decisions_.class).entry(d));

return db.run(Select.from(ApprovalRequests_.class).byId(id)).single(ApprovalRequests.class);
}   // returning the value sets the result and completes the event

// in RepServiceHandler (@ServiceName(RepService_.CDS_NAME)) – unbound function of RepService
@On(event = OpenCountContext.CDS_NAME)
public void openCount(OpenCountContext ctx) {
long n = db.run(Select.from(ApprovalRequests_.class).where(r -> r.status().eq("N"))).rowCount();
ctx.setResult((int) n);
}

Point

Detail

Registration

@On with no attributes: CAP derives event and entity from the argument types – the style of the SAP bookshop sample; @On(event = …, entity = …) works too

Instance key

ctx.getCqn() is a CqnSelect on the bound instance; CqnAnalyzer reads its keys

Parameters

typed getters on the context, e.g. ctx.getReason() for reject(reason)

Result

ctx.setResult(…) or a return value – both complete the event

Status check without code

@flow.status with @from / @to (page 04, Part 8.3) – add the cds-feature-flow dependency in srv/pom.xml

HTTP

same URLs as Node.js once @path is equal: POST …/ApprovalRequests(ID=…)/ManagerService.approve

  • reject (ApprovalRequestsRejectContext) is the same method with status R: a @Before throws ServiceException(ErrorStatuses.BAD_REQUEST, …) when ctx.getReason() is blank (CR3), the @On writes reason to the request and the decision comment. Put the shared logic into a private method decide(String id, String outcome, String reason).
  • Emitting RequestDecided and 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

cds-starter-cloudfoundry or cds-starter-k8s bring authentication support (cds-feature-identity, Spring Security, SAP security libraries); active when an XSUAA or IAS binding exists

Authentication mode

cds.security.authentication.mode: never, model-relaxed (default since CAP Java 5: only @requires/@restrict endpoints need a login), model-strict (unannotated endpoints need a login too) or always

Mock users (local)

cds.security.mock.users in application.yaml, used only without a service binding

Current user in code

ctx.getUserInfo() or inject UserInfo: getName(), hasRole("Manager"), isAuthenticated(), getAttributeValues("region")

Locale

ctx.getParameterInfo().getLocale()

# srv/src/main/resources/application.yaml – local profile only
spring:
config.activate.on-profile: default
cds:
security:
mock:
users:
- name: mia
roles: [ Rep ]
attributes:
region: [ EMEA ]
- name: raj
roles: [ Rep ]
attributes:
region: [ APAC ]
- name: lena
roles: [ Manager ]
  • 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

mvn spring-boot:run                     # from the project root ->  http://localhost:8080
# index page lists services and $metadata; log in with a mock user (e.g. lena) for ManagerService

URL="http://localhost:8080/odata/v4/manager/ApprovalRequests(ID=<uuid>)"
curl -u lena: -X POST "$URL/ManagerService.reject" \
-H "Content-Type: application/json" -d '{"reason":"Margin below 5 %"}'

Task

How

Run

mvn spring-boot:run, or start Application.main() in the IDE (debugging like any Spring app)

Fast restart

mvn cds:watch (CDS build, restart on model changes; with Spring Boot DevTools a fast reload – DevTools are required on Windows)

Same URLs as Node.js

set @path: 'manager' (and 'rep') on the services – default paths can differ between runtimes

Tests

Spring Boot tests (@SpringBootTest, @AutoConfigureMockMvc) with MockMvc against the OData endpoints; @WithMockUser("lena") runs a test as a mock user; or call services directly; → see CAP › 12 · Testing, Plugins, Observability & Performance

Build for BTP

cds build + MTA (cds add mta) → Cloud Foundry or Kyma, → see CAP › 08 · Databases & Deployment

Part 11 – Node.js vs Java

Comparison grid of CAP Node.js and CAP Java: stack, handler code, typing, queries, database client, errors, user, local run, feature reach and when to choose

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'

r.setStatus("N") on List<ApprovalRequests>

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

req.params / req.subject

CqnAnalyzer on ctx.getCqn()

Business error

req.reject(409, 'Already decided')

throw new ServiceException(ErrorStatuses.CONFLICT, "Already decided")

Collect field errors

req.error(…)

ctx.getMessages().error(…)

Current user

req.user.id, req.user.is('Manager')

getUserInfo().getName(), hasRole("Manager")

Local start

cds watch (port 4004)

mvn spring-boot:run (port 8080)

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