CAP Domain Modeling
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Before an application can show an expense claim, it has to know what a claim is: which fields it has, who owns it, and
that its items belong to it and disappear with it. In CAP this description is called the domain model, and it is the
most important file of a project, because the database tables, the web service and the interface metadata are all
produced from it. This page teaches how to write that model with the CAP modeling language CDS. It covers entities and
keys, the ready-made building blocks cuid and managed, the difference between an association (a reference) and a
composition (a part-of relationship), translated texts with localized, and aspects, which let you add to an entity
from another file. A small teaching model for the expense claims of Example Trading Co. (EX01) is built and run for real
in a scratch folder on 2026-11-13: the SQL and OData metadata that the compiler generates, the seed data and the web
requests with $expand shown below are real output. The page is written against CAP Node.js 10.2 (@sap/cds 10.2.2,
command line tools @sap/cds-dk 10.2.1, Node.js 22.12 or newer) and CAP Java 5.2 (Java 21 or newer, Java 25
recommended). The model is plain CDS, so the same files serve both runtimes, and it can be run on a developer machine
without an account. Deploying it to SAP BTP, on the Cloud Foundry or the Kyma runtime, needs an SAP BTP account and is
not run here. SAP BTP is still the documented name, and SAP now presents the SAP BTP capabilities as part of SAP
Business AI Platform.
Before you read
-
CAP Getting Started: the
cdscommand, the foldersdb/,srv/andapp/, and howcds watchstarts a server; this page reuses that setup. -
CAP Concepts: what CDS, CSN and generic providers are; this page puts the modeling part of those ideas to work.
-
CDS Associations and Compositions (ABAP): the same two ideas in the CDS dialect of ABAP; reading both shows what carries over and what does not.
-
A first contact with relational tables (a table, a primary key, a foreign key) is enough; the listings are short.
Key terms
-
CDS (Core Data Services): the text language in which CAP models data and services.
-
Entity: a named structure of typed elements with a primary key; in a relational database it becomes a table.
-
Association: a reference from one entity to another that does not make the target depend on the source.
-
Composition: a contained-in relationship in which the child entries belong to one parent and are created, read and deleted together with it.
-
Aspect: a reusable bundle of elements or annotations that can be included in an entity or added to it with
extend. -
Deep insert: one request that creates a parent entry together with its child entries.
-
Generic provider: the built-in CAP code that serves, validates and fills in data from the model alone.
The running example
The teaching model describes what a clerk at Example Trading Co. (EX01) handles every week: an employee files an expense
claim, a claim holds several items (a train ticket, a dinner) and a few free-text notes, and every item has a category
that is shown in the user’s language. It reuses the namespace and the entity name of the lab project of this site
(sap.guide.expenses, Claims) but is larger: it adds employees, categories, items and notes. It is a teaching model,
not SAP software, and the page shows all of its files.
CAP can draw a class diagram of a model. The command cds compile db/schema.cds --to mermaid writes Mermaid text, and
the environment variables CDS_MERMAID_MIN, CDS_MERMAID_NAMESPACES and CDS_MERMAID_ASSOCNAMES make it show only the
used entities and the names of the relations. The text below is the real output of that command on the model of this
page. An arrow with a filled diamond marks a composition, a plain arrow an association, and the label is the name of the
element.
CDS_MERMAID_MIN=true CDS_MERMAID_NAMESPACES=false CDS_MERMAID_ASSOCNAMES=true cds compile db/schema.cds --to mermaid
Source: real output of cds compile --to mermaid (the options are described in the cds compile section of the
CAP command line interface page; the project had the options CDS_MERMAID_ELEMENTS=keys set as well, which does not change the arrows)
Two entities appear that the model of this page never wrote: sap.common.Currencies comes from the type Currency of
the shared model @sap/cds/common, and Claims.notes is the entity that CAP generates for the inline composition
notes. Both are explained below.
Entities, keys and types
An entity is declared with the keyword entity, a name and a list of elements, each with a name and a type. The domain
modeling guide describes entities as the data of a domain that become tables in relational persistence models, and its
naming conventions are worth following from the first file: entity and type names start with a capital letter, elements
with a lowercase letter, entities are plural (Claims) and types singular, and a name does not repeat its context
(Claims.title, not Claims.claimTitle).
entity Employees : cuid {
name : String(60);
claims : Association to many Claims on claims.employee = $self;
}
Source: excerpt of the model of this page, naming conventions from CAP: Domain Modeling
The built-in types the guide lists include UUID, Boolean, Date, Time, DateTime, Timestamp, Integer,
Int32, Double, Decimal, String, LargeString, Binary and LargeBinary. The model uses String(80) for a
title and Decimal(9,2) for an amount with two decimal places. A project that has many fields of the same kind can name
a type with type, but the guide asks for restraint: custom types pay off only when they are reused.
The guide recommends simple, technical, immutable primary keys, and prefers UUIDs for them. Its reasons: a UUID is unique
across systems, a client can create one before saving, and a parent and its children can be inserted in one transaction
without waiting for a database sequence to hand out the parent’s number. It adds that the generic service providers of
both runtimes fill an UUID key in automatically on insert, and that a UUID must be treated as an opaque value, never
parsed or validated for its format.
The building blocks of @sap/cds/common
CDS ships a small prebuilt model, @sap/cds/common, of reusable types and aspects. The guide on common types describes
three aspects there: cuid, managed and temporal. Importing them is one line:
using { cuid, managed, Currency } from '@sap/cds/common';
Source: first line of db/schema.cds in the model below, CAP: Common Types and Aspects
cuid: a canonical key
entity Claims : cuid is the short form of an entity that starts with key ID : UUID. The compiler writes the unfolded
result like this (the whole model of the page is compiled with cds compile db --to cdl, and the output is shortened to
the entity Employees):
$ cds compile db --to cdl
...
entity sap.guide.expenses.Employees : cuid {
key ID : UUID;
name : String(60);
claims : Association to many sap.guide.expenses.Claims on claims.employee = $self;
};
Source: real output of cds compile db --to cdl (shortened to one entity), CAP: Common Types and Aspects, aspect cuid
The output keeps the include : cuid and also lists the key it added, so one entity is both written the short way and
shown in full. The same command shows what managed adds to Claims.
managed: who changed it and when
managed adds four elements, createdAt, createdBy, modifiedAt and modifiedBy, and annotates them so that the
generic provider fills them in. The guide describes the rule: data of this kind is filled in automatically and cannot
be written by an external client, and the payload of a request is cleansed. The deep insert request in the section on
compositions sends the field createdBy with the value mallory on purpose, and the response shows what the server did with it:
"createdAt": "2026-11-13T14:25:17.610Z",
"createdBy": "anonymous",
"modifiedAt": "2026-11-13T14:25:17.610Z",
"modifiedBy": "anonymous",
Source: real response of the deep insert request below (shortened to the four managed fields), rule from CAP: Domain Modeling, Managed Data
The server stored anonymous, the user of the development setup with mocked authentication, and not mallory. In a
deployed application the value is the authenticated user. The guide adds that the same behavior can be written for
single elements with the annotations @cds.on.insert and @cds.on.update and the pseudo variables $now and $user,
which is what managed does internally.
Currency, Country and Language
The same shared model offers the types Country, Currency and Language, each a reference to a code list entity
(sap.common.Currencies and so on) that also holds translated names. In the model below currency : Currency therefore
becomes a column currency_code and an association to sap.common.Currencies, which is why that entity appears in the
diagram above although the model never declared it.
The model, in full
This is the whole teaching model. The first file defines the data, the second adds to it from outside (the aspects
section explains why), the third is the service that makes Claims, Employees and Categories visible. The lab file
modules/ROOT/examples/sap-lab/expenses/db/schema.cds is smaller: it has only Claims with title, status and
amount.
using { cuid, managed, Currency } from '@sap/cds/common';
namespace sap.guide.expenses;
aspect Described {
remarks : String(200);
}
entity Employees : cuid {
name : String(60);
claims : Association to many Claims on claims.employee = $self;
}
entity Categories : cuid {
name : localized String(40);
}
entity Claims : cuid, managed, Described {
title : String(80);
status : String(1) default 'N';
amount : Decimal(9,2);
currency : Currency;
employee : Association to Employees;
items : Composition of many ClaimItems on items.claim = $self;
notes : Composition of many {
key pos : Integer;
text : String(200);
};
}
entity ClaimItems : cuid {
claim : Association to Claims;
category : Association to Categories;
description : String(80);
amount : Decimal(9,2);
}
Source: db/schema.cds of the teaching model, written for this page from the syntax of CAP: Domain Modeling
using { sap.guide.expenses as db } from './schema';
extend db.Claims with {
project : String(20);
}
annotate db.Claims with {
title @title : 'Claim title';
};
Source: db/extensions.cds of the teaching model, CAP: Aspect-oriented Modeling
using { sap.guide.expenses as db } from '../db/schema';
service ExpenseService {
entity Claims as projection on db.Claims;
entity Employees as projection on db.Employees;
entity Categories as projection on db.Categories;
}
Source: srv/expense-service.cds of the teaching model, CAP: Domain Modeling
The service exposes three entities and nothing else; ClaimItems, Claims.notes and Currencies appear in it anyway,
for reasons explained next. The seed data of the lab is CSV files in db/data/, named after the namespace and the
entity. The initial data guide shows the pattern sap.capire.bookshop-Books.csv and, for translated texts,
sap.capire.bookshop-Books.texts.csv, which this model follows:
db/data/sap.guide.expenses-Employees.csv
db/data/sap.guide.expenses-Categories.csv
db/data/sap.guide.expenses-Categories.texts.csv
db/data/sap.guide.expenses-Claims.csv
db/data/sap.guide.expenses-ClaimItems.csv
db/data/sap.guide.expenses-Claims.notes.csv
Source: file names of the teaching model, naming pattern from CAP: Adding Initial Data
$ cat db/data/sap.guide.expenses-Claims.csv
ID,title,status,amount,currency_code,employee_ID,remarks
a1111111-1111-1111-1111-111111111111,Customer visit Chicago,N,128.50,USD,e1111111-1111-1111-1111-111111111111,Example Trading Co. (EX01)
$ cat db/data/sap.guide.expenses-ClaimItems.csv
ID,claim_ID,category_ID,description,amount
b1111111-1111-1111-1111-111111111111,a1111111-1111-1111-1111-111111111111,c1111111-1111-1111-1111-111111111111,Train ticket,98.50
b2222222-2222-2222-2222-222222222222,a1111111-1111-1111-1111-111111111111,c2222222-2222-2222-2222-222222222222,Client dinner,30.00
$ cat db/data/sap.guide.expenses-Claims.notes.csv
up__ID,pos,text
a1111111-1111-1111-1111-111111111111,1,Receipts attached
$ cat db/data/sap.guide.expenses-Categories.texts.csv
locale,ID,name
de,c1111111-1111-1111-1111-111111111111,Reisen
de,c2222222-2222-2222-2222-222222222222,Verpflegung
Source: seed files of the teaching model (the files for Employees and Categories hold two rows each and are not shown), file layout from CAP: Adding Initial Data
The column names show the compiler’s naming of generated elements: the foreign key of the association employee is
employee_ID, the key of the target joined to the association name, and the foreign key of the inline composition
notes is up__ID, a backlink named up_ joined to ID. Running cds watch with this model loaded all six files
into the in-memory SQLite database and served the service at /odata/v4/expense:
$ PORT=4118 cds watch
[cds] - loaded model from 3 file(s):
srv/expense-service.cds
db/schema.cds
node_modules/@sap/cds/common.cds
...
> init from db/data/sap.guide.expenses-Employees.csv
> init from db/data/sap.guide.expenses-Claims.notes.csv
> init from db/data/sap.guide.expenses-Claims.csv
> init from db/data/sap.guide.expenses-ClaimItems.csv
> init from db/data/sap.guide.expenses-Categories.texts.csv
> init from db/data/sap.guide.expenses-Categories.csv
/> successfully deployed to in-memory database.
...
[cds] - serving ExpenseService {
at: [ '/odata/v4/expense' ],
decl: 'srv/expense-service.cds:2'
}
[cds] - server listening on { url: 'http://localhost:4118' }
Source: real output of cds watch (shortened: color codes and blank lines removed; this run was made before db/extensions.cds was added, which then showed up in the file list), CAP Getting Started
Associations: a reference to another entity
An association says that an entry points at an entry of another entity. employee : Association to Employees is the
simplest form: a managed to-one association. The guide’s word "managed" means that CAP adds the foreign key column and
the join condition for you, and it recommends managed associations for every to-one relation. The generated column in
the SQL below is employee_ID.
A to-many association needs the backlink written down, because the compiler cannot guess it. In Employees the element
claims : Association to many Claims on claims.employee = $self reads: the claims whose employee is this employee.
The guide notes that the condition can compare a backlink association to $self, or a backlink foreign key to the own
key. An association is read with $expand. The employees and their claims, the second employee has none:
curl -s 'http://localhost:4118/odata/v4/expense/Employees?$expand=claims($select=title,amount)' | python3 -m json.tool
{
"@odata.context": "$metadata#Employees",
"value": [
{
"ID": "e1111111-1111-1111-1111-111111111111",
"name": "Ana Torres",
"claims": [
{
"title": "Customer visit Chicago",
"amount": "128.50",
"ID": "a1111111-1111-1111-1111-111111111111"
}
]
},
{
"ID": "e2222222-2222-2222-2222-222222222222",
"name": "Ben Carter",
"claims": []
}
]
}
Source: real response (JSON pretty-printed with python3 -m json.tool), CAP: Domain Modeling, Associations
The key ID is added to each expanded entry although $select did not name it; the response always carries the key.
CDS has no dedicated many-to-many association. The guide resolves it with a link entity that holds two to-one associations, and notes that a composition of an inline aspect (shown below) removes some of the noise. The model of this page has no many-to-many relation.
Compositions: parts that belong to one parent
A composition is an association with a promise: the target entries are parts of the source entry. The reference
documentation puts it as "contained-in", and the domain guide lists the three things the runtimes do for it out of the
box: a deep insert or update fills in whole document structures, deleting the root deletes the parts (a cascaded
delete), and composition targets are exposed in the service automatically. In Claims, the line
items : Composition of many ClaimItems on items.claim = $self says that the items of a claim are parts of it. The
on condition uses the backlink claim, which is an ordinary association in ClaimItems.
Auto-exposure and the entity you cannot call directly
The service of this page lists Claims, Employees and Categories. The compiler still produced ClaimItems and
Claims.notes in the service, as the metadata further below shows. They were exposed because they are composition
targets. The service lets a client reach them only through their parent. A direct request is refused with this answer:
curl -s -i 'http://localhost:4118/odata/v4/expense/ClaimItems'
HTTP/1.1 405 Method Not Allowed
{"error":{"message":"Entity \"ExpenseService.ClaimItems\" is not explicitly exposed as part of the service","code":"ENTITY_IS_AUTOEXPOSED","@Common.numericSeverity":4}}
Source: real response (shortened to the status line and the body), auto-exposure rule from CAP: Domain Modeling, Compositions
The message says that the entity is not explicitly exposed. An entity line of its own in the service is the way to expose it explicitly; this page did not run that variant.
Reading the parts with $expand
A claim and its parts come back in one request. The request also shows the composition of the inline aspect, notes:
curl -s 'http://localhost:4118/odata/v4/expense/Claims?$select=title,amount&$expand=items($select=description,amount),notes($select=pos,text)' | python3 -m json.tool
{
"@odata.context": "$metadata#Claims",
"value": [
{
"title": "Customer visit Chicago",
"amount": "128.50",
"items": [
{
"description": "Train ticket",
"amount": "98.50",
"ID": "b1111111-1111-1111-1111-111111111111"
},
{
"description": "Client dinner",
"amount": "30.00",
"ID": "b2222222-2222-2222-2222-222222222222"
}
],
"notes": [
{
"pos": 1,
"text": "Receipts attached"
}
],
"ID": "a1111111-1111-1111-1111-111111111111"
}
]
}
Source: real response (JSON pretty-printed), CAP: Domain Modeling, Compositions
The notes carry no ID because their key is pos together with the generated backlink.
Compositions of aspects: the inline form
The element notes : Composition of many { key pos : Integer; text : String(200); } has no entity behind it. The guide
calls this a composition of aspects, and the language reference explains the result: the compiler adds an entity whose
name is the name of the parent entity followed by the name of the element, here Claims.notes, with a backlink named
up_. The unfolded entity, as cds compile db --to cdl prints it:
entity sap.guide.expenses.Claims.notes {
key up_ : Association[1..1] to sap.guide.expenses.Claims not null;
key pos : Integer;
text : String(200);
};
Source: real output of cds compile db --to cdl (shortened to one entity), CAP: CDL, Managed Compositions of Aspects
The generated entity has two keys, the backlink and pos, which is why the table below has the primary key up__ID, pos and why the seed file needs both columns. A named aspect can be used instead of an inline one:
Items : Composition of many OrderItems with aspect OrderItems { ... } is unfolded the same way, according to the
language reference. The reference also warns about compositions of one: they are discouraged for entities, with very
limited draft support and no extensive modification over paths.
Deep insert: one request, three kinds of rows
A composition lets a client send the claim, its items and its notes in a single request body:
{
"title": "Workshop Boston",
"amount": 75.00,
"currency_code": "USD",
"employee_ID": "e2222222-2222-2222-2222-222222222222",
"createdBy": "mallory",
"items": [
{ "description": "Taxi", "category_ID": "c1111111-1111-1111-1111-111111111111", "amount": 40.00 },
{ "description": "Lunch", "category_ID": "c2222222-2222-2222-2222-222222222222", "amount": 35.00 }
],
"notes": [ { "pos": 1, "text": "Deep insert test" } ]
}
Source: deep.json, a request body written for this page, deep insert behavior from CAP: Domain Modeling, Compositions
curl -s -i -X POST 'http://localhost:4118/odata/v4/expense/Claims' -H 'Content-Type: application/json' -d @deep.json
HTTP/1.1 201 Created
{
"@odata.context": "$metadata#Claims/$entity",
"ID": "cbf159fd-b51d-46c3-9643-6b7d8e7425af",
...
"title": "Workshop Boston",
"status": "N",
"amount": "75.00",
"currency_code": "USD",
"employee_ID": "e2222222-2222-2222-2222-222222222222",
"items": [
{
"ID": "1a17b9d8-2fdb-494d-b000-11e391f9cb57",
"claim_ID": "cbf159fd-b51d-46c3-9643-6b7d8e7425af",
"category_ID": "c1111111-1111-1111-1111-111111111111",
"description": "Taxi",
"amount": "40.00"
},
...
],
"notes": [
{
"up__ID": "cbf159fd-b51d-46c3-9643-6b7d8e7425af",
"pos": 1,
"text": "Deep insert test"
}
],
"project": null
}
Source: real response (the body is JSON pretty-printed with python3 -m json.tool; shortened where the line ... stands: the managed fields shown earlier, remarks and the second item are left out)
The server answered with status 201, generated a UUID for the claim and for each item, and filled in the backlink
claim_ID and up__ID itself: the client never had to know the new claim’s key to insert its children. The default
status N was applied, and project is the element that extensions.cds added.
Cascaded delete
Deleting a composition root deletes its parts, and the compiler records that in the service metadata (below). The
service does not expose the items, so the count of rows was made with a small test script using the CAP test helper,
cds.test, started in the same project. The script deletes the seeded claim through the service and counts the rows of
the two child tables through the database service before and after:
import cds from '@sap/cds'
import { test } from 'node:test'
const { DELETE } = cds.test(import.meta.dirname)
const out = (...a) => process.stderr.write(a.join(' ') + '\n')
const count = async e => (await cds.db.run(SELECT.one.from(e).columns('count(*) as n'))).n
const items = 'sap.guide.expenses.ClaimItems', notes = 'sap.guide.expenses.Claims.notes'
test('cascade', async () => {
out('before: items', await count(items), 'notes', await count(notes))
const res = await DELETE('/odata/v4/expense/Claims(a1111111-1111-1111-1111-111111111111)')
out('DELETE Claims', res.status)
out('after: items', await count(items), 'notes', await count(notes))
})
$ node --test check-cascade.test.mjs
before: items 2 notes 1
DELETE Claims 204
after: items 0 notes 0
Source: check-cascade.test.mjs of the teaching model and its real output (shortened to the three lines the script prints), cascaded delete rule from CAP: Domain Modeling, Compositions; the helper cds.test is the one the lab test test/service.test.js uses
An association does not cascade
An association has no such promise. The employee Ben Carter owns the new claim "Workshop Boston". Deleting the employee
through the service is accepted, and the claim keeps its foreign key; reading the claim with $expand=employee finds no
target:
curl -s -o /dev/null -w "DELETE employee %{http_code}\n" -X DELETE 'http://localhost:4118/odata/v4/expense/Employees(e2222222-2222-2222-2222-222222222222)'
curl -s 'http://localhost:4118/odata/v4/expense/Claims?$filter=title%20eq%20%27Workshop%20Boston%27&$expand=employee($select=name)&$select=title,employee_ID'
DELETE employee 204
{"@odata.context":"$metadata#Claims","value":[{"title":"Workshop Boston","employee_ID":"e2222222-2222-2222-2222-222222222222","employee":null,"ID":"abe6731c-9c71-4656-ad18-d0afb5c573e2"}]}
Source: real output of the two requests, run on a fresh server after a new deep insert of the same body (so the claim has a new generated key, unlike the deep insert response above), semantics from CAP: Domain Modeling, Associations and Compositions
The generated SQL, shown further down, contains no foreign key constraint, so the database did not object either. The language reference points to a section on database constraints in the CAP database guide for projects that want to add them. Which relation is which is therefore a modeling decision with a runtime effect: a claim item makes no sense without its claim, so it is a composition; a claim only refers to the employee who filed it, so it is an association.
Association or composition
| Question | Association | Composition |
|---|---|---|
What does it mean? |
The entry refers to an entry that lives on its own. |
The target entries are parts of the source entry. |
Deep insert and update |
Not done: the target must exist, and its key is given as a foreign key ( |
Done: the parts are sent inside the parent’s body, and their keys and backlinks are filled in. |
Delete of the source |
Does not touch the target (shown above). |
Deletes the parts (shown above); the metadata says |
Exposure in a service |
The target must be exposed with its own entity line in the service. |
The target is exposed automatically, and is reachable through its parent. |
Typical use |
Employee of a claim, category of an item, currency. |
Items of a claim, lines of an order, notes of a claim. |
Source: the three runtime rules of compositions in CAP: Domain Modeling, Compositions and the runs above
The ABAP page CDS Associations and Compositions describes the same split in ABAP CDS: a composition makes a child entity depend on its parent, with a to-parent association pointing back.
Localized data: texts in the user’s language
The category names are the example. In the model, name : localized String(40) is the whole declaration. CAP unfolds it
into a second entity Categories.texts that holds the translations, plus two associations on the base entity, as the
localized data guide shows. The unfolded text entity, as the compiler printed it for this model:
entity sap.guide.expenses.Categories.texts : sap.common.TextsAspect {
@title : '{i18n>LanguageCode}'
key locale : sap.common.Locale(14);
@odata.containment.ignore : true
key ID : UUID;
name : String(40);
};
Source: real output of cds compile db --to cdl (shortened to one entity), CAP: Localized Data
The base entity keeps the original text (the guide: all original texts stay in the source entity, which saves a join when a translation is missing), and the texts table holds one row per entry and language. The generated SQL below has both tables and a view that reads them with a fallback.
The runtime picks the language from the request. The guide says that the preferred locale is taken from request
parameters, user settings or the Accept-Language header, and that the pseudo variable $user.locale carries it into
the query. The $expand of a claim with its items and their categories, sent with the header:
curl -s -H 'Accept-Language: de' 'http://localhost:4118/odata/v4/expense/Claims?$select=title&$expand=items($select=description;$expand=category($select=name))' | python3 -m json.tool
{
"@odata.context": "$metadata#Claims",
"value": [
{
"title": "Customer visit Chicago",
"items": [
{
"category": {
"name": "Reisen",
"ID": "c1111111-1111-1111-1111-111111111111"
},
"description": "Train ticket",
"ID": "b1111111-1111-1111-1111-111111111111"
},
{
"category": {
"name": "Verpflegung",
"ID": "c2222222-2222-2222-2222-222222222222"
},
"description": "Client dinner",
"ID": "b2222222-2222-2222-2222-222222222222"
}
],
"ID": "a1111111-1111-1111-1111-111111111111"
}
]
}
Source: real response (JSON pretty-printed), request header behavior from CAP: Localized Data
Reading the categories directly gave the English names Travel and Meals from the base entity without the header and
Reisen and Verpflegung with it (request Categories?$select=name). The translated rows are also readable as a
collection of their own: Categories(<ID>)/texts returned the entry with locale de.
The guide states two limits worth knowing: the keys of an entity with localized elements must not be associations, and
localized inside structured elements is ignored.
Aspects: adding to an entity from another place
An aspect is a named or anonymous bundle of elements or annotations. The reference calls CDS aspects a mechanism for the
separation of concerns, with extend and annotate as the two directives, and says that consumers always see the
effective model, so the separation is invisible outside the model files.
The model uses all three forms. The named aspect Described holds one element, remarks, and Claims includes it
the way it includes cuid and managed: entity Claims : cuid, managed, Described. The unfolded Claims table below
has the column remarks right after the four managed columns. The file db/extensions.cds shows the other two:
extend db.Claims with { project : String(20); } adds an element to an entity defined elsewhere, and
annotate db.Claims with { title @title : 'Claim title'; } attaches an annotation. Both took effect in the generated
output: the SQL table has a column project, and the metadata has a label for title.
The domain guide recommends this for secondary concerns, for authorization annotations that a security team maintains in its own file, and for user interface annotations that belong in the frontend model, so that the core domain model stays short and readable. A later page of this section covers the authorization annotations, and the Fiori annotations belong with the user interface pages.
What the compiler generates
The compiler turns the model into SQL for the database and into OData metadata for the service. Both are plain text that can be read and compared, which is the best way to understand a model.
SQL
cds compile db srv --to sql prints the whole script, 155 lines for this model. The table of the entity Claims
shows all the contributions of the model: the managed columns, the included remarks, the foreign keys currency_code
and employee_ID and the extension project:
$ cds compile db srv --to sql
CREATE TABLE sap_guide_expenses_Claims (
ID NVARCHAR(36) NOT NULL,
createdAt TIMESTAMP_TEXT,
createdBy NVARCHAR(255),
modifiedAt TIMESTAMP_TEXT,
modifiedBy NVARCHAR(255),
remarks NVARCHAR(200),
title NVARCHAR(80),
status NVARCHAR(1) DEFAULT 'N',
amount REAL_DECIMAL(9, 2),
currency_code NVARCHAR(3),
employee_ID NVARCHAR(36),
project NVARCHAR(20),
PRIMARY KEY(ID)
);
...
Source: real output of cds compile db srv --to sql (shortened to the first table), CAP: CAP-Level Database Integration
There is no column for items or claims: associations and compositions to many are not stored, they are joins. The
two generated tables show the other half of the model:
CREATE TABLE sap_guide_expenses_Claims_notes (
up__ID NVARCHAR(36) NOT NULL,
pos INTEGER NOT NULL,
text NVARCHAR(200),
PRIMARY KEY(up__ID, pos)
);
...
CREATE TABLE sap_guide_expenses_Categories_texts (
locale NVARCHAR(14) NOT NULL,
ID NVARCHAR(36) NOT NULL,
name NVARCHAR(40),
PRIMARY KEY(locale, ID)
);
...
CREATE VIEW localized_sap_guide_expenses_Categories AS SELECT
L_0.ID,
coalesce(localized_1.name, L_0.name) AS name
FROM (sap_guide_expenses_Categories AS L_0 LEFT JOIN sap_guide_expenses_Categories_texts AS localized_1 ON localized_1.ID = L_0.ID AND localized_1.locale = session_context( '$user.locale' ));
Source: real output of cds compile db srv --to sql (shortened to three objects), CAP: Localized Data
The view is the fallback of the localized data guide in practice: it takes the translated name when the left join
finds one for the user’s locale and the base name otherwise. The target database changes the types, not the model.
With --dialect hana the same table comes out with the types of SAP HANA:
$ cds compile db srv --to sql --dialect hana
CREATE TABLE sap_guide_expenses_Claims (
ID NVARCHAR(36) NOT NULL,
createdAt TIMESTAMP,
...
amount DECIMAL(9, 2),
...
);
Source: real output of cds compile db srv --to sql --dialect hana (shortened; the dialect option is listed by cds compile --help with the values sqlite, h2, postgres and hana), CAP command line interface
The first command printed TIMESTAMP_TEXT and REAL_DECIMAL(9, 2) and the second TIMESTAMP and DECIMAL(9, 2), the
two columns that differ in the part shown. Running the model on SAP HANA Cloud is part of deploying to SAP BTP, on
either runtime, and needs an SAP BTP account; the page on the SAP BTP environments describes the two runtimes and this
page does not run a deployment.
OData metadata
cds compile db srv --to edmx prints the metadata document that the OData service publishes at $metadata. The part
for Claims shows the navigation properties and, on the two compositions, the delete rule that the guide describes:
<NavigationProperty Name="employee" Type="ExpenseService.Employees" Partner="claims">
<ReferentialConstraint Property="employee_ID" ReferencedProperty="ID"/>
</NavigationProperty>
<Property Name="employee_ID" Type="Edm.Guid"/>
<NavigationProperty Name="items" Type="Collection(ExpenseService.ClaimItems)" Partner="claim">
<OnDelete Action="Cascade"/>
</NavigationProperty>
<NavigationProperty Name="notes" Type="Collection(ExpenseService.Claims_notes)" Partner="up_">
<OnDelete Action="Cascade"/>
</NavigationProperty>
Source: real output of cds compile db srv --to edmx (shortened to four lines of the entity type Claims), CAP: Domain Modeling, Compositions
The association employee has a referential constraint and no delete rule; items and notes carry OnDelete Action="Cascade". The entity Claims_notes is the OData name of Claims.notes, with the two keys up__ID and pos,
and the compiler also added the entity sets ClaimItems, Claims_notes, Categories_texts, Currencies and
Currencies_texts to the container, which is the auto-exposure of the previous sections made visible. The label set
by annotate appears as <Annotation Term="Common.Label" String="Claim title"/> on ExpenseService.Claims/title.
CAP Java and the domain model
CDS is the modeling language of both runtimes, and the domain guide says that the generic service providers of Java and
Node.js alike fill in UUID keys on insert. The model of this page was run on CAP Node.js 10.2 only; it was not run
with CAP Java 5.2. The first steps of a Java project are on the page CAP Getting
Started and in the later page on CAP Java; the Java classes that handle events are a different topic.
Common modeling mistakes
| Mistake | What happens and what to do |
|---|---|
A composition used for a plain reference, such as an employee of a claim |
Deleting the claim would delete the employee’s data if the target were really part of it, and a service would expose the target automatically. Use an association when the target lives on its own. |
An association used for the items of a claim |
Deep insert and cascaded delete are not done for it, so the items stay behind when the claim is deleted. Use a composition. |
A to-many association without an |
The domain guide says the condition is needed when targeting a database; write the backlink as |
A client sends |
The generic provider overwrites managed fields; the request of this page shows |
Composite or business keys everywhere |
The guide prefers a single simple technical key, a UUID, because keys are used in every join; keep business numbers as ordinary elements. |
|
The localized data guide lists this as a restriction. |
Source: rules from CAP: Domain Modeling and CAP: Localized Data, consequences as shown by the runs above
Summary
-
A CAP domain model is CDS: entities with typed elements and a key, written the short way with
cuidfor a UUID key andmanagedfor the four change-tracking fields that the generic provider fills in and clients cannot write. -
An association is a reference (
employee_ID), a composition is a part-of relationship: deep insert, cascaded delete and automatic exposure apply to compositions only, as the runs on this page showed, and a composition target can be read only through its parent unless the service names it. -
Composition of many { ... }with an inline aspect generates an entity named after the parent and the element (Claims.notes) with a backlinkup_; a named aspect included in an entity adds its elements. -
localizedgenerates a.textsentity and a view with fallback; the language comes from the request, for example theAccept-Languageheader. -
extendandannotateadd to an entity from another file, so core models stay clean. -
cds compile --to sqland--to edmxshow exactly what the database and the OData service receive; the dialect option changes the database types, not the model.
Try it
To do this by hand, follow the guide Model a Domain and Add Custom Logic in CAP: it adds associations, a composition, a validation handler and an action.