CDS Associations and Compositions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Business data lives in many tables that point at each other: an expense claim points at the employee who filed it, and at its list of items. In a database you join the tables by hand every time you need fields from more than one. A CDS association lets you describe that link once, give it a name that starts with an underscore, and then use the name wherever you need the related data, in other views and in ABAP programs. Nothing is read from the related table until somebody follows the name, so an association costs nothing until it is used. A composition is a special association for parent and child data, such as a claim and its items, and it is the structure on which the RAP business object is built. After this page you can read and write the association and composition lines of a CDS view entity, choose a cardinality, follow an association with a path expression, and predict when a join is created. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). View entities and the association syntax shown here apply to ABAP Cloud, to classic Standard ABAP, on premise and in the Public Edition alike. Every CDS and ABAP SQL listing on this page requires an SAP system; not run here. Only the small ABAP listing near the end runs, in the local playground, and it shows the effect of a left outer join with plain internal tables.
Before you read
-
Dictionary Tables and Structures: the tables
zexp_claimand the way a table is declared; the examples here read from them. -
ABAP SQL: Joins, CTEs and Window Functions: inner and left outer joins, which are what an association turns into.
-
ABAP SQL Basics: the
SELECTstatement that reads a CDS view like a table. -
CDS view entities themselves, with the select list, casts and parameters, have a page of their own that precedes this one; this page only repeats the lines needed to define an association.
Key terms
-
CDS association: a named, reusable link from one CDS entity to another with a join condition, evaluated only when used.
-
Cardinality: how many rows of the target can match one row of the source, for example many to one.
-
Path expression: a chain of association names separated by periods (in CDS) or backslashes (in ABAP SQL) that reaches a field of a related entity.
-
Exposure: listing an association in the select list so that other entities and ABAP SQL can use it.
-
CDS composition: a pair of to-child and to-parent associations that makes a child entity depend on its parent for its existence.
-
Root entity: the top parent of a composition tree, the entity that stands for the whole RAP business object.
What an association is
An association connects the entity in which you write it, the association source, to another entity, the association target, with an ON condition. The target can be a database table, another view entity, a projection view, a table function or one of a few other entity kinds. The association has a name; the documentation recommends starting it with an underscore, and the examples on this page do. If you leave the name out, it is the name of the target.
The basic form of the statement, inside the SELECT of a view entity, is association [cardinality] [to] target as _name on condition. It goes between the from clause and the opening brace of the select list. Three rules for the ON condition matter to a newcomer:
-
fields of the association source are written with the name of the data source in front, or with its alias;
-
fields of the target are written with the association name in front, such as
_Employee.EmployeeId; -
a field that is part of the select list of the current view is written with the prefix
$projection, such as$projection.EmployeeId.
An association on its own does nothing. Official documentation states that "as soon as an association is used in a path expression" it is turned into a join internally; until then no join exists. The benefit over a hand-written join is that the link is defined once and reused in different places, and that you do not have to repeat a complex join condition.
Cardinality
The cardinality says how many rows of the target can belong to one row of the source. It documents the shape of the data and the SAP HANA optimizer uses it to leave out joins that are not needed, so it must match the real data. Written in words, it has a source part and a target part: of many to one, of one to many, of exact one to one and so on, where each side is exact one, one or many. The documentation recommends this form. It can also be written as numbers in square brackets, [0..1] or [*], which gives only the target side; this is the form older examples use.
The rules to remember are these. If you give no cardinality, the association is treated as many to one in the word form and as to-one in the numeric form. The cardinality is descriptive, not prescriptive: it does not force the data to match. If it is wrong the result is undefined, and the documentation shows a view whose association was left at the default although the data was to-many, so that two reads of the same view returned a different number of rows. A to-many association used for a field in the select list multiplies the rows of the result, because each source row appears once for every matching target row. Finally, the two forms must not be mixed in one association.
For the expense claim, the employee of a claim is many to one: many claims can belong to one employee, and a claim has one employee. The items of a claim are one to many, and in a composition, as shown below, the same relation is written composition of exact one to many.
| Written in words | Numeric form | Example in the running example |
|---|---|---|
|
|
claim to employee |
|
|
employee to claims |
|
|
a claim to its one summary row |
The numeric forms in the second column are written from the range rule of the documentation (min..max, a missing min meaning 0); the word forms are the recommended ones.
Defining and exposing an association
The listing defines the employee side first, a small view entity over a table zexp_employee (with the columns employee_id, name and cost_centre), and then the claim view with an association to it. The association is exposed: its name appears in the select list without a field name. Only an exposed association can be used by other views and by ABAP SQL. The same view also uses _Employee.FullName in the select list, which makes the association part of the claim view’s own query. The tables and the names ZI_ExpEmployee and ZI_ExpClaim belong to the running Expense claims example. It requires an SAP system; not run here.
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Employee'
define view entity ZI_ExpEmployee
as select from zexp_employee
{
key employee_id as EmployeeId,
name as FullName,
cost_centre as CostCentre
}
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Expense claim with employee'
define view entity ZI_ExpClaimWithEmployee
as select from zexp_claim
association of many to one ZI_ExpEmployee as _Employee
on $projection.EmployeeId = _Employee.EmployeeId
{
key claim_id as ClaimId,
employee_id as EmployeeId,
status as Status,
_Employee,
_Employee.FullName as EmployeeName
}
Source: ABAP Keyword Documentation: CDS DDL - CDS View Entity, SELECT, exposing an association and CDS DDL - CDS View Entity, ASSOCIATION
Two details in the listing come from the rules above. The ON condition uses $projection.EmployeeId because EmployeeId is in the select list, and it has to be: when an association is exposed, the source fields of its ON condition must be listed in the select list so that a join can be built when somebody follows the association. The second detail is that the claim view lists _Employee and also reads _Employee.FullName. The first line only publishes the association; the second one instantiates it, so the database sees a join only because of the second line.
Path expressions
A path expression follows one or more associations to reach a field. In CDS it is written with periods, _Employee.FullName. The first association is either defined in the current view or exposed by one of its data sources; every further association must be exposed by the target of the one before it, so _Employee._CostCentre.Name works only when ZI_ExpEmployee exposes _CostCentre. A target that exposes no association ends the path; for tables and DDIC-based views no further association can follow.
Each association in the path can carry attributes in square brackets: a cardinality, the join type (inner or left outer) and a filter condition. For example, _Employee[inner].FullName asks for an inner join instead of the default, so claims whose employee does not exist drop out of the result. The documentation’s own example of that form is _scarr[inner].carrname.
Where the path is used decides the default join type:
| Where the path expression is used | Join type | What happens |
|---|---|---|
as the data source after |
inner join |
only rows with a match remain |
a field in the select list |
left outer join |
all source rows remain, fields of the target are initial when nothing matches |
an operand in |
left outer join |
a path in |
exposed only, no field read |
no join |
the association is published but the database is not asked anything |
An association defined in one view and exposed can also be used by a view that reads from it. In the next listing ZI_ExpClaimEmployeeName reads from ZI_ExpClaimWithEmployee and follows the exposed _Employee. The join is created in this second view, when it is activated, and not in the view that defined the association. It requires an SAP system; not run here.
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity ZI_ExpClaimEmployeeName
as select from ZI_ExpClaimWithEmployee
{
key ClaimId,
_Employee.CostCentre as CostCentre
}
How an association path becomes a join
When a path expression is compiled, the association source becomes the left side and the association target the right side of a join, and the ON condition of the association becomes the join condition. In the select list the join is a left outer join: every claim stays in the result, and a claim whose employee row is missing still appears, with an initial FullName. The picture shows the two ways to say the same thing.
For comparison, here is the join a developer would otherwise write by hand in ABAP SQL. It is an illustration of the meaning, not the statement that the database receives, because the actual generated statement is shown in the documentation as a screenshot. It requires an SAP system; not run here.
SELECT claim~ClaimId,
employee~FullName AS EmployeeName
FROM zi_expclaimwithemployee AS claim
LEFT OUTER JOIN zi_expemployee AS employee
ON claim~EmployeeId = employee~EmployeeId
INTO TABLE @DATA(by_join).
Source: ABAP Keyword Documentation: CDS DDL - CDS View Entity, Associations and Joins and SELECT, FROM JOIN
What a left outer join does with a missing match, and what a to-many step does to the number of rows, can be shown with ordinary internal tables. The listing below performs the same two lookups with LOOP and READ TABLE. It runs in the local playground and printed the output shown. Claim C-1002 points at an employee that does not exist, so its name is empty but its row remains; claim C-1001 has two items and therefore appears twice, while C-1002 has none and appears once.
REPORT zassoc.
TYPES: BEGIN OF ty_claim,
claim_id TYPE c LENGTH 10,
employee_id TYPE n LENGTH 8,
END OF ty_claim.
TYPES ty_claims TYPE STANDARD TABLE OF ty_claim WITH EMPTY KEY.
TYPES: BEGIN OF ty_employee,
employee_id TYPE n LENGTH 8,
full_name TYPE c LENGTH 20,
END OF ty_employee.
TYPES ty_employees TYPE SORTED TABLE OF ty_employee WITH UNIQUE KEY employee_id.
TYPES: BEGIN OF ty_item,
claim_id TYPE c LENGTH 10,
item_no TYPE i,
END OF ty_item.
TYPES ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.
DATA(claims) = VALUE ty_claims( ( claim_id = 'C-1001' employee_id = '00001234' )
( claim_id = 'C-1002' employee_id = '00009999' ) ).
DATA(employees) = VALUE ty_employees( ( employee_id = '00001234' full_name = 'Alex Example' ) ).
DATA(items) = VALUE ty_items( ( claim_id = 'C-1001' item_no = 1 )
( claim_id = 'C-1001' item_no = 2 ) ).
WRITE / 'Left outer join on the employee (to one): one row per claim'.
LOOP AT claims INTO DATA(claim).
DATA(name) = VALUE string( ).
READ TABLE employees INTO DATA(employee) WITH KEY employee_id = claim-employee_id.
IF sy-subrc = 0.
name = employee-full_name.
ENDIF.
WRITE / |{ claim-claim_id } name: '{ name }'|.
ENDLOOP.
WRITE / 'Left outer join on the items (to many): one row per item, or one row when there is none'.
LOOP AT claims INTO claim.
DATA(found) = abap_false.
LOOP AT items INTO DATA(item) WHERE claim_id = claim-claim_id.
found = abap_true.
WRITE / |{ claim-claim_id } item: { item-item_no }|.
ENDLOOP.
IF found = abap_false.
WRITE / |{ claim-claim_id } item: (none)|.
ENDIF.
ENDLOOP.
Output:
Left outer join on the employee (to one): one row per claim
C-1001 name: 'Alex Example'
C-1002 name: ''
Left outer join on the items (to many): one row per item, or one row when there is none
C-1001 item: 1
C-1001 item: 2
C-1002 item: (none)
Using an association in ABAP SQL
An exposed association is available to ABAP programs. In ABAP SQL the path is written with a backslash in front of each association, and the field name is attached with a hyphen, \_Employee-FullName. A path in the column list is again a left outer join by default, and one after FROM is an inner join. The association must be exposed by the CDS view entity that the statement reads. The listing reads the claim view and follows _Employee. It requires an SAP system; not run here.
SELECT ClaimId,
\_Employee-FullName AS EmployeeName
FROM zi_expclaimwithemployee
INTO TABLE @DATA(claims).
The ABAP SQL syntax in the keyword documentation is the one with a backslash and a hyphen. A cardinality can be given in the square brackets after the association, as in the documentation example \_spfli[ MANY TO MANY ]-connid, and a syntax warning or error is raised when the cardinality does not fit how the path is used.
Compositions: parent and child entities
A composition is an association with an extra meaning: the child cannot exist without the parent. A sales order item belongs to exactly one order, and an expense item belongs to exactly one claim. This relation is what RAP uses to shape a business object, so the documentation describes a composition as made of two halves.
-
The to-parent association is written in the child with
association to parent. It points to the parent entity and carries theONcondition. -
The to-child association is written in the parent with
composition of. It has noONcondition of its own: the condition is generated from the to-parent association of the child.
The child must define its to-parent association first; the other order is a syntax error. The top of the structure is the root entity, written define root view entity. A root has no parent, and its children can have children of their own, which together form the composition tree of the business object.
The rules for each half, as the documentation states them:
| Rule | To-parent association (child) | To-child association (parent) |
|---|---|---|
Keyword |
|
|
|
required; only |
none; generated from the child’s to-parent association |
Cardinality |
not given, generated as to-one |
words form needs the source side |
Default filter |
not allowed |
not allowed |
Exposure |
the name must appear once in the select list |
the name must appear once in the select list |
Targets |
cannot be the entity itself |
cannot be the entity itself, cannot be a root entity |
A child can be the target of exactly one to-child association, so it has exactly one parent. Fields of a composition target cannot be read in the select list or the WHERE clause of the parent; the composition is for structure, not for pulling child fields into the parent. In another view that reads from the parent, the exposed composition behaves like a regular association and can be used in a path expression.
The running example turns the claim and its items into a business object. The child comes first because the parent may only name it once it exists. Both listings require an SAP system; not run here.
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Expense claim item'
define view entity ZI_ExpItem
as select from zexp_item
association to parent ZI_ExpClaim as _Claim
on $projection.ClaimId = _Claim.ClaimId
{
key claim_id as ClaimId,
key item_no as ItemNo,
category as Category,
@Semantics.amount.currencyCode: 'CurrencyCode'
amount as Amount,
currency_code as CurrencyCode,
_Claim
}
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Expense claim'
define root view entity ZI_ExpClaim
as select from zexp_claim
composition of exact one to many ZI_ExpItem as _Items
association of many to one ZI_ExpEmployee as _Employee
on $projection.EmployeeId = _Employee.EmployeeId
{
key claim_id as ClaimId,
employee_id as EmployeeId,
status as Status,
currency_code as CurrencyCode,
@Semantics.amount.currencyCode: 'CurrencyCode'
total_amount as TotalAmount,
_Items,
_Employee
}
Source: ABAP Keyword Documentation: CDS DDL - CDS View Entity, ASSOCIATION TO PARENT, COMPOSITION and ROOT
Notice that _Employee is an ordinary association even though it sits in the root: it points to an entity outside the business object and carries a normal ON condition. Only _Items is a composition. The association that points from ZI_ExpItem back to the claim, _Claim, is declared with association to parent and its condition uses the key field ClaimId of the parent with the $projection prefix, as the rules require. Cyclic dependencies between entities should be avoided because they cause problems in mass activations.
The key and annotation lines of the two listings, @Semantics.amount.currencyCode for the amount and the key fields, are explained in Currencies, Units and Conversions.
What older books show, and what has changed
Older material, including books written before view entities, differs from current documentation in three places.
-
Older examples define DDIC-based CDS views. The documentation now marks them obsolete, and new development uses CDS view entities. The association syntax is the same idea, but the view entity form on this page is the one to write.
-
Older examples give the cardinality only in square brackets, such as
association [0..1] to. The documentation recommends the word form, because it improves query performance in some scenarios, and it accepts the numeric form for compatibility. -
Compositions,
association to parentanddefine root view entitybelong to the RAP model. A source that predates RAP cannot describe them; a parent-child relation there is an ordinary one-to-many association that nothing enforces.
Common mistakes
-
A cardinality that does not match the data. The result is undefined, and a to-many association that was left at the default many-to-one gives different row counts depending on the select list. State the cardinality in words.
-
A to-many field in the select list. Each source row is repeated for every target row. If one row per claim is wanted, do not select fields of
_Itemsin the claim view. -
A to-many path in
WHERE. A path inWHEREorHAVINGmust be to-one, or carry a filter that the documentation’s1:addition declares unique. -
Forgetting to expose the
ONfields. When an association is exposed, the source fields of itsONcondition must be in the select list. -
A to-child association before the to-parent one. The child defines
association to parentfirst; the reverse order is a syntax error.
Summary
-
A CDS association is a named, reusable link between two CDS entities; nothing is joined until a path expression uses it.
-
The cardinality documents how many target rows match a source row. Write it in words and make sure it is true; the default is many to one.
-
An association is exposed by listing its name in the select list; only an exposed association can be used from other views and from ABAP SQL.
-
A path expression turns the association into a join: an inner join after
FROMand a left outer join elsewhere, unless the attributes say otherwise. -
A composition is a to-child association in the parent plus a to-parent association in the child; with a root entity it forms the composition tree of a RAP business object.
-
Older books show DDIC-based views and numeric cardinality; current code uses view entities and the word form.
References
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, SELECT, Associations
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, ASSOCIATION
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, cardinality
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, path_expr
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, Associations and Joins
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, COMPOSITION
-
ABAP Keyword Documentation: CDS DDL - CDS View Entity, ASSOCIATION TO PARENT