ERPClimb logoERPClimb
CAP Java service runtime
SAP Cloud Application Programming Modelintermediate 5 min read

CAP Java service runtime — SAP Guided Tutorial

Free sample lesson · open to everyone

Key takeaway

How the CAP Java stack works on Spring Boot: generated POJO interfaces from CDS, event handler classes with @Before/@On/@After, the persistence service, and how errors and transactions behave compared with Node. js.

By the end of this part: Separate Java SDK conventions from Node.js examples

What's inside

  • Real project scenario
  • Step-by-step explanation
  • Code example
  • Common mistakes
  • Best practices
  • Interview angle
  • 4 practice questions
  • 2 interview questions
  • Counts toward a certificate
In this lessonShow sections

Visual overview

CAP Java service runtime — learning sheetFlow: CDS model → Maven plugin: POJOs → EventHandler classes → Spring Boot runtime. Key ideas: PROJECT STRUCTURE; TYPED MODEL ACCESS; EVENT HANDLERS; ERRORS AND TRANSACTIONS. Watch out: Generated classes are build output — change the CDS model, rebuild, never edit the generated Java.ERPClimb.com / CAP / LESSON 5/12 / LEARNING SHEETCAP Java service runtime1 · HOW IT FLOWS1CDS model2Maven pluginPOJOs3EventHandlerclasses4Spring Bootruntime2 · KEY IDEAS EXPLAINEDProject Structure`cds init bookshop --java` (or the Mavenarchetype) creates db/, srv/ with a Maven module,and a Spring Boot Application class.`mvn spring-boot:run` builds CDS, generates codeand starts the app; H2 or SQLite is used locally.Typed Model AccessFor entity Books the plugin generates `Books`(data accessor interface) and `Books_` (querybuilder model).Queries use CQL builders:`Select.from(Books_.class).where(b ->b.stock().lt(10))`.Event Handlers`@Component @ServiceName(CatalogService_.CDS_NAME)public class CatalogHandler implementsEventHandler { ... }``@Before(event = CqnService.EVENT_CREATE, entity =Orders_.CDS_NAME) void validate(List<Orders>orders) { ... }`Errors And Transactions`throw newServiceException(ErrorStatuses.BAD_REQUEST,"Quantity must be positive");` rejects…Use Messages (`messages.error(...).target(...)`)to collect several field-level errors.3 · REMEMBER · WATCH OUTRememberCAP Java runs on Spring Boot; the cds-maven-plugin compiles CDS andgenerates typed interfaces (e.g. Books, Books_).Handlers are Spring beans implementing EventHandler, annotated with@ServiceName and @Before/@On/@After.The same phase model as Node.js: validate in @Before, implement in@On, adjust in @After.!Watch outGenerated classes are build output —change the CDS model, rebuild, neveredit the generated Java.4 · IN A REAL PROJECTA Java team bypassed CQL and used a JdbcTemplate query for performance. In the multitenant deployment it readdata from the wrong tenant schema, because raw JDBC skipped CAP's tenant-aware data source routing. Rewritingthe query with CQL and a projection restored tenant isolation and performed just as well.Original ERPClimb learning sheet • Verify against your SAP release and edition

The situation: a real project scenario

A Java team bypassed CQL and used a JdbcTemplate query for performance. In the multitenant deployment it read data from the wrong tenant schema, because raw JDBC skipped CAP's tenant-aware data source routing. Rewriting the query with CQL and a projection restored tenant isolation and performed just as well.

Explanation

CAP Java runs on Spring Boot, and the cds-maven-plugin compiles your CDS model into typed Java interfaces as part of the build — for an entity Books you get both Books, a typed data accessor, and Books_, a query-builder model used to reference the entity in CQL statements. These are generated build artifacts: when the CDS model changes, you rebuild and the interfaces regenerate, so the generated classes should never be hand-edited — any fix belongs in the CDS model, not in the generated Java.

Event handlers are plain Spring beans. A class annotated @Component and @ServiceName(CatalogService_.CDS_NAME) that implements EventHandler registers its methods against a specific service, and methods are further annotated @Before, @On, or @After for a given event and entity, for example @Before(event = CqnService.EVENT_CREATE, entity = Orders_.CDS_NAME).

This is the same three-phase model used in CAP Node.js: @Before validates and enriches incoming data, @On implements or replaces the operation itself, and @After adjusts the result before it is returned. Custom actions follow the same pattern but use a generated context class, such as @On(event = SubmitOrderContext.CDS_NAME), and the handler finishes by calling ctx.setResult(...).

Rejecting a request is done by throwing new ServiceException(ErrorStatuses.BAD_REQUEST, "Quantity must be positive"), which rolls back the transaction the request is running in; the Messages API lets you collect several field-level errors instead of failing on the first one.

Because the whole request executes inside a Spring-managed transaction, any work that must happen only after a successful commit — calling an external system, for instance — belongs in a transaction listener or an outbox, never inside an @After handler, since an @After handler can still run even if something later in the same transaction causes a rollback.

For data access, typed CQL builders give you compile-time safety: Select.from(Books_.class).where(b -> b.stock().lt(10)) built and then run through the persistence service, for example db.run(select).listOf(Books.class). Staying inside CQL and the persistence service (rather than dropping to raw JDBC) matters beyond convenience — it is how CAP's authorization checks, tenant-aware routing, and other cross-cutting concerns stay active for every query.

To get hands-on: scaffold a Java CAP project and start it with mvn spring-boot:run; add a @Before CREATE handler on Orders that validates quantity; implement an action handler using its generated context class; then change the CDS model, rebuild, and watch the generated interfaces regenerate. By the end you should be able to trace a request from the incoming HTTP call through your @Before, @On, and @After methods and explain exactly which one causes a rollback on exception.

Quick check before you go on

Question 1 of 1

In CAP Java, what generates the Books and Books_ interfaces?

Code example

ABAP Code
@Component@ServiceName(CatalogService_.CDS_NAME)public class CatalogHandler implements EventHandler {   @Before(event = CqnService.EVENT_CREATE, entity = Orders_.CDS_NAME)  public void validate(List<Orders> orders) {    for (Orders o : orders) {      if (o.getQuantity() == null || o.getQuantity() < 1)        throw new ServiceException(ErrorStatuses.BAD_REQUEST, "Quantity must be positive");    }  }}

Watch out

Common mistakes

  • Editing generated Java classes instead of the CDS model.
  • Bypassing CQL and writing raw JDBC SQL, losing authorization and tenant handling.
  • Catching ServiceException and continuing, so invalid data is committed.
  • Calling external systems inside @After before the transaction commits.

Do this

Best practices

  • Keep handlers thin; put reusable domain logic in Spring services tested with unit tests.
  • Use generated typed accessors and CQL builders for compile-time safety.
  • Use Spring profiles to switch local H2/SQLite and cloud HANA/XSUAA cleanly.

In the interview

Interview angle

For Java roles, show you understand the generated model (Books vs Books_), the handler annotations, ServiceException for errors, and why you stay inside CQL and the persistence service so authorization and multitenancy keep working.

Practice this lesson

Original educational case studies for SAP consultants, not official SAP certification exam questions. Verify product edition and implementation details against the current SAP documentation.

Quick check

0 of 3 questions attempted

Question 1 of 3

How do you reject an invalid request in a CAP Java @Before handler?

Practise this in an interview

Answer in your own words and get instant feedback, the way an interviewer would judge it.

1Compare CAP Node.js and CAP Java. How would you choose for a project?

2How do you implement and test an action in CAP Java?

Was this lesson helpful?

Keep exploring

Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.