CAP Java
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
The SAP Cloud Application Programming Model (CAP) lets you describe business data and services in a modeling language and write only the business rules by hand. CAP has two runtimes that read the same models: one for Node.js and one for Java. This page is for developers who already know Java and want the Java runtime. You will create a CAP Java project, see what the generator produces, write an event handler class that validates expense claims, and read data with query builders instead of SQL text. It is written for CAP Java 5.2, which needs Java 21 or newer (SAP recommends Java 25) and Apache Maven 3.9.14 or newer. The CAP command line tools are the ones of CAP Node.js 10.2 (@sap/cds-dk 10.2.1), because they generate the project even for a Java application. Everything on this page runs on a laptop and works the same wherever the application is later deployed; the choice between the SAP BTP Cloud Foundry environment and the Kyma environment only matters at deployment, where it changes which starter bundle you add. The product is still documented as SAP Business Technology Platform (SAP BTP), and SAP now presents BTP capabilities as part of SAP Business AI Platform; the pages cited at the end say so.
The project listings on this page were run for real: the project was generated with cds init --java, built with Maven and started on a JDK installed on the author’s machine, then called over HTTP. Nothing on this page needs an SAP BTP account. The pieces that do need one (the Cloud Foundry and Kyma starter bundles) are described from the official pages and labeled "requires an SAP BTP account; not run here".
Before you read
-
CAP Concepts: models, services, events, queries and protocol adapters; this page puts the Java notation to them.
-
CAP Getting Started: installing the command line tools and the project layout, which Java projects share.
-
Java Getting Started and Java Build and Tooling: installing a JDK and reading a Maven
pom.xml. -
Spring Boot Core Concepts: beans,
@Componentand constructor injection, which CAP Java handler classes use. -
Reading Java annotations and lambdas: Annotations and Reflection and Lambdas and Method References.
Key terms
-
Event handler: a Java method that CAP calls before, on or after an event, in which your business logic lives.
-
Generic provider: built-in handlers that serve reads and writes from the model alone, so that a service works before you write any Java.
-
Protocol adapter: the part of the runtime that turns web requests, here OData V4, into CAP events.
-
CQN (Core Query Notation): the plain-data form of a query that the Java builders produce and the database service turns into SQL.
-
CQL (Conceptual Query Language): the database-independent query language whose Java form is the
Selectbuilder. -
CDS (Core Data Services): the modeling language of CAP, shared by the Node.js and Java runtimes.
-
Application service: the service CAP creates for every service in the model; it is the one your handlers extend.
-
Persistence service: the database client of CAP, which accepts queries on any stored entity.
The running example
The example is the same teaching model as in the other CAP pages of this site: expense claims that employees of Example Trading Co. (EX01) submit. The model is shown in full here, because this page builds a new Java project from it. The domain model is a copy of the CAP lab’s db/schema.cds.
using { cuid, managed } from '@sap/cds/common';
namespace sap.guide.expenses;
entity Claims : cuid, managed {
title : String(80);
status : String(1) default 'N';
amount : Decimal(9,2);
}
Source: CAP: Core Concepts
The service file differs from the lab’s in one line. The lab marks the entity with @odata.draft.enabled, which switches on the draft mode of SAP Fiori elements; this page leaves that annotation out to keep the Java handler small. The service therefore is a teaching variant of the lab’s service.
using { sap.guide.expenses as db } from '../db/schema';
service ExpenseService {
entity Claims as projection on db.Claims;
}
Source: CAP: Core Concepts
The lab also seeds one claim in db/data/sap.guide.expenses-Claims.csv, which this page copies unchanged: the claim Train ticket with status N and amount 45.50.
Setting up the tools
The official Getting Started page for CAP Java lists three tools: the CDS tools (cds-dk), a Java VM ("Java 21 is the minimum requirement, but we recommend using Java 25") and Apache Maven (at least version 3.9.14). It checks them with three commands (not Java-specific output; run on any machine with the tools installed).
cds --version
java --version
mvn --version
Source: CAP Java: Getting Started
The check is worth doing, because the build refuses to start on an older Java. The author’s default Java is 17. When cds init --java ran with it, the generator failed in its second Maven call (real output, shortened to the lines that matter).
[ERROR] Failed to execute goal com.sap.cds:cds-maven-plugin:5.2.0:add (default-cli) on project expenses-java-parent:
[ERROR] The plugin com.sap.cds:cds-maven-plugin:5.2.0 has unmet prerequisites:
[ERROR] Required Java version 21 is not met by current version: 17.0.14
Source: real output of cds init expenses-java --java on Java 17.0.14 with @sap/cds-dk 10.2.1; the Java requirement is stated at CAP Java: Getting Started
The generator removed the half-created folder after the failure. All following listings ran with a JDK 21 for the generator and a JDK 26 for the build, both already installed on the machine, as explained in the next section.
Creating the project
There are two ways to create a CAP Java project, and the official page shows both. The first calls the Maven archetype directly (Maven prompts for the group ID and the artifact ID, and the artifact ID is also the name of the new root folder).
mvn archetype:generate -DarchetypeArtifactId="cds-services-archetype" -DarchetypeGroupId="com.sap.cds" -DarchetypeVersion="RELEASE" -DinteractiveMode=true
Source: CAP Java: Getting Started
The archetype coordinates are therefore group com.sap.cds and artifact cds-services-archetype. The page on building projects lists the command-line options of the archetype, among them -DgroupId, -DartifactId, -Dpackage, -DincludeModel=true (adds a minimal sample model), -DodataVersion=[v2|v4] (default v4), -DinMemoryDatabase=[h2|sqlite] (default h2) and -DjdkVersion=[21|25] (default 25). The last default matters for readers on Java 21: pass -DjdkVersion=21.
The second way is the CDS command line. It needs no Maven knowledge, because it runs the archetype for you. The next command ran for real (requires CAP Node.js tools, Maven and a JDK 21 or newer; no account). The output is shortened: Maven’s download lines are omitted and the repeated reactor summaries are cut where marked.
cds init expenses-java --java
Adding facet: java
The derived package name 'customer.expenses-java' is not a valid Java package name. Using 'customer.expenses_java' instead.
using Maven archetype version 5.2.0
[INFO] Using following parameters for creating project from Archetype: cds-services-archetype:5.2.0
[INFO] Parameter: groupId, Value: customer
[INFO] Parameter: artifactId, Value: expenses-java
[INFO] Parameter: version, Value: 1.0.0-SNAPSHOT
[INFO] Parameter: package, Value: customer.expenses_java
[INFO] Parameter: inMemoryDatabase, Value: h2
[INFO] Parameter: jdkVersion, Value: 25
[INFO] Parameter: includeModel, Value: false
[INFO] Parameter: odataVersion, Value: v4
[INFO] Parameter: cdsdkVersion, Value: 10.1.2
[INFO] Parameter: includeIntegrationTest, Value: false
[INFO] Parameter: persistence, Value: true
[INFO] Parameter: targetPlatform, Value: local
[INFO] AddMojo: Added dependency `com.sap.cds:cds-adapter-odata-v4` to '.../expenses-java/srv/pom.xml'.
[INFO] AddMojo: Added dependency `com.h2database:h2` to '.../expenses-java/srv/pom.xml'.
[INFO] Project created from Archetype in dir: .../expenses-java
...
Successfully initialized CAP project
Continue with: code expenses-java
Source: real output of cds init expenses-java --java (@sap/cds-dk 10.2.1, CDS Maven plugin 5.2.0), shortened where marked; the command is described at CAP Java: Getting Started
Three details of the output are worth reading. The tool derived the Java package from the project name and replaced the hyphen, which is not allowed in a package name. The archetype version is 5.2.0, the CAP Java release of this page. And the defaults are the ones the archetype page lists: H2 as the local database, OData V4, no sample model, and target Java 25, with a @sap/cds-dk version of 10.1.2 in the generated package.json, older than the 10.2.1 command line that ran. Because the project targets Java 25, the build of the next sections ran on an installed JDK 26; a project generated with -DjdkVersion=21 would build on JDK 21.
The generated project
The files that the generator wrote, as listed by the shell (real output; node_modules is left out).
expenses-java/.cdsrc.json
expenses-java/.gitignore
expenses-java/package-lock.json
expenses-java/package.json
expenses-java/pom.xml
expenses-java/srv/pom.xml
expenses-java/srv/src/main/java/customer/expenses_java/Application.java
expenses-java/srv/src/main/resources/application.yaml
Source: real output of find in the scratch project after cds init expenses-java --java; the layout is described at CAP Java: Getting Started
The official layout table gives each folder a job: db holds the database content such as the domain model, srv holds the service definitions and the Java back-end code (the Java sources are in srv/src/main/java), and srv/src/gen/java receives the compiled CDS model and the generated accessor interfaces after the first mvn compile. The project has two Maven modules, the parent pom.xml in the root and the srv module that holds the application. The class Application is a plain Spring Boot application.
package customer.expenses_java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Source: real file srv/src/main/java/customer/expenses_java/Application.java of the generated project
The parent pom.xml imports the bill of materials cds-services-bom (the official page recommends it to keep all CAP modules in step) and sets the property cds.services.version to 5.2.0 and jdk.version to 25. Its dependency list in srv/pom.xml is short.
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-starter-spring-boot</artifactId>
</dependency>
<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-adapter-odata-v4</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Source: excerpt of the real srv/pom.xml of the generated project; the starter bundles are described at CAP Java: Building CAP Java Applications
Each dependency has one job. The starter cds-starter-spring-boot bundles what a Spring Boot web application needs, with no protocol chosen. The artifact cds-adapter-odata-v4 is the OData V4 protocol adapter. H2 is the in-memory database for local work. The generated srv/pom.xml also configures the CDS Maven plugin with a chain of steps that run at every build: clean, install Node.js, run npm ci (which installs @sap/cds-dk from package.json), resolve, run build --for java and a deploy to H2, and finally the generate goal that writes the Java interfaces for the model. Its options in this project are basePackage cds.gen, betterNames, cqnServiceGetters, linkedInterfaces and interfacesForAspects. The official building page describes the plugin’s tasks as installing Node.js and the CDS development kit, running arbitrary CDS commands and generating Java classes for type-safe access.
Adding the model and building
To use the example model, copy schema.cds, the service file and the CSV file into db/, srv/ and db/data/ of the new project. Then build once. The first build is also what creates the generated sources: the official page says the IDE shows missing classes until mvn compile has run once, and for IntelliJ IDEA the folder srv/src/gen/java must be marked as generated sources root.
mvn compile
[INFO] GenerateMojo: Class generation finished successfully
[INFO] Compiling 41 source files with javac [debug release 25] to target/classes
[INFO] Reactor Summary for expenses-java parent 1.0.0-SNAPSHOT:
[INFO] expenses-java parent ............................... SUCCESS [ 0.139 s]
[INFO] expenses-java ...................................... SUCCESS [ 2.717 s]
[INFO] BUILD SUCCESS
Source: real output of mvn compile in the scratch project on JDK 26 with Maven 3.9.16, shortened to the lines that matter; the step is described at CAP Java: Getting Started
After the build, the folder srv/src/gen/java/cds/gen/expenseservice holds four generated files for this model: ExpenseService.java, ExpenseService_.java, Claims.java and Claims_.java. They are the typed vocabulary the handler uses, and you do not edit them. The next table says what each one is, from the generated code and the official pages on typed access.
| Generated type | What it gives you |
|---|---|
|
A data accessor interface that extends |
|
A query builder interface: |
|
A constant interface: |
|
A service interface that extends |
Source: real generated files in srv/src/gen/java/cds/gen/expenseservice of the scratch project; concepts at CAP Java: Working with Data and CAP Java: Building CAP Java Applications
Event handlers
In CAP everything that happens at run time is an event sent to a service. The generic providers handle the standard events for a service from the model. Your own code joins in with event handlers: ordinary Java methods that you mark with an annotation saying in which phase of the event they run. The official page describes three phases that run one after another. Before is meant for filtering, validation and other preprocessing of the incoming data. On is meant for the core processing of the event; as soon as an On handler completes the event, the remaining On handlers are skipped. After starts only after the On phase completed successfully and is meant for post-processing the result or for side effects. A handler that throws an exception ends the processing immediately.
Source: CAP Java: Event Handlers
The generic providers run around your handlers: the page lists the order as generic framework handlers, then your handlers marked early, then your ordinary Before, On and After handlers, then your handlers marked late, then the generic handlers again. A handler class has three parts, all visible in the next listing.
-
The class implements the marker interface
EventHandler; the page says CAP needs it to find the class among all beans and to scan it for handler methods. -
In Spring Boot the class must also be a bean, which
@Componentprovides, so Spring can inject dependencies into it. -
The annotation
@ServiceNamenames the default service for all methods of the class. The page recommends the generated constant (ExpenseService_.CDS_NAME) over a string.
Each method carries @Before, @On or @After, with the attributes event and entity. The constants CqnService.EVENT_CREATE, EVENT_READ, EVENT_UPDATE, EVENT_UPSERT and EVENT_DELETE name the standard events, and Claims_.CDS_NAME names the entity. An OData POST becomes a CREATE event, a GET becomes READ, and PATCH and PUT become UPDATE.
A validation handler
This is the Java version of the lab’s Node.js handler. The Node.js handler of the lab is a class with an init() method that registers one function.
import cds from '@sap/cds'
export default class ExpenseService extends cds.ApplicationService {
init() {
this.before('SAVE', 'Claims', req => {
if (req.data.amount < 0) req.error(400, 'Amount must not be negative', 'in/amount')
})
return super.init()
}
}
Source: real file srv/expense-service.js of this site’s CAP lab (modules/ROOT/examples/sap-lab/expenses)
The Java class below does the same check and adds a second rule that reads the database: it refuses a new claim whose title already exists. This second rule is a teaching rule of this page, not a feature of CAP or of the lab. The file is srv/src/main/java/customer/expenses_java/handlers/ExpenseServiceHandler.java, and it compiled and ran (requires JDK 21 or newer and Maven; no account).
package customer.expenses_java.handlers;
import cds.gen.expenseservice.Claims;
import cds.gen.expenseservice.Claims_;
import cds.gen.expenseservice.ExpenseService_;
import com.sap.cds.ql.Select;
import com.sap.cds.services.ErrorStatuses;
import com.sap.cds.services.ServiceException;
import com.sap.cds.services.cds.CqnService;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.Before;
import com.sap.cds.services.handler.annotations.ServiceName;
import com.sap.cds.services.persistence.PersistenceService;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.stereotype.Component;
@Component
@ServiceName(ExpenseService_.CDS_NAME)
public class ExpenseServiceHandler implements EventHandler {
private final PersistenceService db;
public ExpenseServiceHandler(PersistenceService db) {
this.db = db;
}
@Before(event = { CqnService.EVENT_CREATE, CqnService.EVENT_UPDATE }, entity = Claims_.CDS_NAME)
public void validateAmount(List<Claims> claims) {
for (Claims claim : claims) {
if (claim.getAmount() != null && claim.getAmount().compareTo(BigDecimal.ZERO) < 0) {
throw new ServiceException(ErrorStatuses.BAD_REQUEST, "Amount must not be negative");
}
}
}
@Before(event = CqnService.EVENT_CREATE, entity = Claims_.CDS_NAME)
public void rejectDuplicateTitle(List<Claims> claims) {
for (Claims claim : claims) {
var sameTitle = db.run(Select.from(Claims_.class).where(c -> c.title().eq(claim.getTitle())));
if (!sameTitle.listOf(Claims.class).isEmpty()) {
throw new ServiceException(ErrorStatuses.CONFLICT, "A claim titled '{}' exists already", claim.getTitle());
}
}
}
}
Source: real handler of the scratch project, built on CAP Java 5.2; the annotations and signatures are described at CAP Java: Event Handlers, the error API at CAP Java: Indicating Errors, and a handler with the same constructor injection of PersistenceService is in the SAP sample cloud-cap-samples-java
Read the listing from the top. The constructor receives the PersistenceService, the default database client; Spring supplies it, which is why the class has to be a bean. The method validateAmount is registered on two events at once. Its parameter List<Claims> is an entity data argument: the page says that in the Before and On phases the data comes from the query of the request and that changes to it are safe, so a handler can also correct the data before it is stored. Because the annotation names two events, CAP registers the method for both. The handler fails a request by throwing ServiceException. The ErrorStatuses enum maps the failure to an HTTP status: BAD_REQUEST is a 400 and CONFLICT a 409, and without a status the exception defaults to a 500. In the message of the second exception, {} is a placeholder that CAP fills with the argument that follows, a formatting the page documents. The page also describes a second route for validation errors, the Messages API, which collects several errors and ends the Before phase with one exception, and says it is the recommended way for validation errors; a single check like this one can throw directly.
Running it
The command below starts the application (requires JDK 21 or newer and Maven; no account). The extra argument sets the port; without it the official page says to open http://localhost:8080. The startup log is shortened to the lines that name CAP’s own work.
mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=4120
INFO --- Starting Application using Java 26 ...
INFO --- c.s.c.services.impl.utils.CdsModelUtils : Loaded CDS model from CSN resource path 'edmx/csn.json'
INFO --- c.s.c.services.impl.ServiceCatalogImpl : Registered service ExpenseService
INFO --- com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:... user=SA
INFO --- c.s.c.services.impl.ServiceCatalogImpl : Registered service PersistenceService$Default
INFO --- c.s.c.f.s.c.adapter.AdapterBeanFactory : Servlet CdsODataV4Servlet mapped to /odata/v4
INFO --- c.s.c.s.impl.runtime.CdsRuntimeImpl : Registered handler class customer.expenses_java.handlers.ExpenseServiceHandler
INFO --- c.s.c.s.impl.persistence.CsvDataLoader : Filling sap.guide.expenses.Claims from ../db/data/sap.guide.expenses-Claims.csv
INFO --- o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 4120 (http) with context path '/'
INFO --- customer.expenses_java.Application : Started Application in 0.885 seconds
Source: real startup log of the scratch project (CAP Java 5.2, Spring Boot 4.1.1 as set in the generated parent pom.xml), shortened where marked; run instructions at CAP Java: Getting Started
The log shows the pieces of the earlier concepts page at work: the compiled model, the registered ExpenseService, the persistence service on an in-memory H2 database, the OData V4 adapter mapped to /odata/v4 (the default base path in the official page on application services), the registered handler class and the seed claim loaded from the CSV file. Now call the service. The first command reads the claims; the other three send a claim with a negative amount, a claim with an existing title and a valid claim. Only the status line and the body are shown, from the same real session.
curl -i http://localhost:4120/odata/v4/ExpenseService/Claims
curl -i -H 'Content-Type: application/json' -d '{"title":"Taxi","amount":-5}' http://localhost:4120/odata/v4/ExpenseService/Claims
curl -i -H 'Content-Type: application/json' -d '{"title":"Train ticket","amount":10}' http://localhost:4120/odata/v4/ExpenseService/Claims
curl -i -H 'Content-Type: application/json' -d '{"title":"Taxi","amount":12.5}' http://localhost:4120/odata/v4/ExpenseService/Claims
HTTP/1.1 200
{"@context":"$metadata#Claims","value":[{"ID":"11111111-1111-1111-1111-111111111111","createdAt":"2026-11-13T14:25:26.714333Z","createdBy":"system-internal","modifiedAt":"2026-11-13T14:25:26.714333Z","modifiedBy":"system-internal","title":"Train ticket","status":"N","amount":45.50}]}
HTTP/1.1 400
{"error":{"code":"400","message":"Amount must not be negative"}}
HTTP/1.1 409
{"error":{"code":"409","message":"A claim titled 'Train ticket' exists already"}}
HTTP/1.1 201
{"@context":"$metadata#Claims/$entity","ID":"91fe9c2b-189e-4f3f-92d1-b79fae6fc44a","createdAt":"2026-11-13T14:25:35.467652Z","createdBy":"anonymous","modifiedAt":"2026-11-13T14:25:35.467652Z","modifiedBy":"anonymous","title":"Taxi","status":"N","amount":12.5}
Source: real responses of the scratch project, headers other than the status line omitted; behavior described at CAP Java: Event Handlers and CAP Java: Application Services
Each response matches one rule. The read needed no Java at all: the generic provider answered it, and the fields createdAt and modifiedBy come from the managed aspect of the model. The negative amount became HTTP 400 with the handler’s message, the duplicate title became HTTP 409 with the formatted message, and the valid claim was stored with the status default N of the model. A PATCH that sets the amount of the seed claim to -1 also answered 400 in the same session, because the validation method is registered on UPDATE as well. The field createdBy shows anonymous for the claim posted without credentials; the official security page describes mock users for local tests, which the generated project did not configure, and this page does not go further into authentication.
Querying with the CQN builders
The second handler method built a query: Select.from(Claims_.class).where(c -> c.title().eq(claim.getTitle())). This is CQL in Java form. The method from takes the generated query builder interface, and the lambda receives a typed reference to the entity, so c.title() is checked by the Java compiler: a misspelled element does not compile. The result of the builder is a CQN object. To see it, the handler was run once with one extra line that prints the query before running it (the extra line is not part of the listing above).
CQN: {"SELECT":{"from":{"ref":["ExpenseService.Claims"]},"where":[{"ref":["title"]},"=",{"val":"Taxi"}]}}
Source: real output of the scratch project with one added System.out.println of the query; the builders are described at CAP Java: Building CQN Queries
That JSON is a CQN object, the notation that the concepts page describes for both runtimes. A trace line of the same run read CQN SELECT Claims; the official page describes the persistence service as the component that translates CQN to SQL for the database, here H2. The page on query execution lists the ways to take a result apart: listOf(Claims.class) returns a typed list, single(...) returns the one expected row, and first() returns an optional. The official page on building queries shows more builder forms; for example, for its bookshop model (shown here from the page, not run on this page’s model):
Select.from(BOOKS).columns(b -> b.title()).byId(101);
Select.from(BOOKS)
.where(b -> b.author().name().startsWith("A"));
Source: CAP Java: Building CQN Queries; shown from the page, not run here
The first line picks one column of one book by key. The second follows the association from a book to its author inside the lambda, as a path expression. The same page names a text-based form, Select.from("bookshop.Books"), for code that does not use the generated interfaces.
Two services can run a query, and the difference matters. The application service is the facade that clients call and that runs your handlers and the generic providers (authorization and input validation among them). The persistence service is the database client. It is not bound to one service definition and accepts statements on any stored entity, which is why a handler that needs extra data for a check, like rejectDuplicateTitle, uses it. The official page says the persistence service is used inside handlers when additional data must be read for custom validation. The application service, injected as the generated interface ExpenseService, is the one to call when the generic providers and your handlers should run for the call too.
On Cloud Foundry and Kyma
The project above runs locally. To run it on SAP BTP the project needs the starter bundle of the target environment. The official page names them. The bundle cds-starter-cloudfoundry is described as production-ready for the SAP BTP Cloud Foundry environment: it comprises XSUAA authentication, SAP HANA persistence, the Cloud Foundry environment and multitenancy support. The bundle cds-starter-k8s is its counterpart for the SAP BTP Kyma environment. For Cloud Foundry the page shows a command that adds the first one (requires CAP Java and Maven to run the command; the deployment itself requires an SAP BTP account; not run here).
mvn com.sap.cds:cds-maven-plugin:add -Dfeature=CF
Source: CAP Java: Getting Started; not run here
According to the page, this adds cds-starter-cloudfoundry to pom.xml. The same plugin command with -Dfeature=TINY_SAMPLE adds a sample model and with -Dfeature=INTEGRATION_TEST creates the module integration-tests. Running the application on Cloud Foundry or Kyma also needs a SAP HANA database, an XSUAA service instance for the login and a deployment descriptor; they are the subject of the pages on BTP environments and XSUAA and identity, and of the pages CAP Security and Deploying CAP: HANA, XSUAA and MTA, all of which need an SAP BTP account. The Java code of the handler class does not change between the two environments.
Where the Java handler differs from the Node.js one
The two handlers of this page agree on the rule and differ in the way they say it. The Node.js class extends cds.ApplicationService and registers a function in init(); the Java class implements EventHandler and lets annotations register its methods. In Node.js req.data is a plain record; in Java an entity data argument is typed by the generated interface, which still is a map underneath, because Claims extends CdsData. In Node.js the validation error is reported with req.error; in Java it is a thrown ServiceException or a message in the Messages API. Queries are text or fluent objects in Node.js, and builders over generated interfaces in Java. The rest is shared: the same CDS files, the same events, the same generic providers and the same OData URLs.
Summary
-
CAP Java 5.2 needs Java 21 or newer (25 recommended) and Maven 3.9.14 or newer;
cds init <name> --javaruns the Maven archetypecom.sap.cds:cds-services-archetypeand produces a Spring Boot project with a parentpom.xml, thesrvmodule and the H2 database. -
The CDS Maven plugin builds the model and generates Java interfaces (
Claims,Claims_,ExpenseService,ExpenseService_) at every build; runmvn compileonce so that the IDE sees them. -
A handler class implements
EventHandler, is a Spring@Component, names its service with@ServiceNameand marks methods with@Before,@Onand@After; the generic providers run the standard events around your code. -
A handler fails a request with
ServiceExceptionand anErrorStatusesvalue; on the lab model a negative amount returned HTTP 400 and a duplicate title HTTP 409. -
Queries are built with
Select.from(...)over the generated interfaces and run on the persistence service; the builder produces the same CQN as Node.js. -
Cloud Foundry and Kyma differ only in the starter bundle and the deployment, which need an SAP BTP account; the handler code stays the same.