Sub topic 2
CDS view entities and associations as the building block
This chapter covers the CDS view entity, which is the unit every analytical model in the rest of this tutorial is built from. It assumes you know basic SQL (SELECT, JOIN, GROUP BY, aggregate functions), understand S/4HANA business objects such as sales orders and customers, and can tell transactional (OLTP) workloads from analytical (OLAP) ones. You don't need earlier ABAP CDS experience. The examples use hypothetical custom tables, zcustomer and zsales_item, so you can adapt them to your own system.
What a CDS view entity is
A CDS view entity is a data definition written in ABAP Core Data Services (CDS). You create it in ABAP Development Tools (ADT) in Eclipse, as a data definition source file. The system activates it, and the database (SAP HANA in S/4HANA) executes it as a SQL view. The view entity holds no data of its own. Every time a consumer reads it, the database evaluates the underlying SELECT against live data.
This is why embedded analytics can work on transactional data without a separate copy. An analytical query is a stack of CDS views, and each read is pushed down to the database.
View entities are the current form of CDS view. The older "CDS DDIC-based view" needed a separate SQL view name and a second repository object. A view entity has a single object, so there is no @AbapCatalog.sqlViewName annotation to maintain. For new development, use view entities. You will still meet DDIC-based views in standard content that predates them.
Anatomy of a view entity
Here is the dimension view from the tutorial's running example:
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Customer'
@Analytics.dataCategory: #DIMENSION
define view entity ZI_CustomerDim
as select from zcustomer
{
key customer_id as CustomerId,
@Semantics.text: true
customer_name as CustomerName,
country as Country
}It has four parts:
- Annotations before
define. These are metadata for the view as a whole.@EndUserText.labelgives a readable name.@AccessControl.authorizationCheckstates whether an access control is required.@Analytics.dataCategoryis covered in a later chapter. - The
define view entityheader. It names the view. The name is global in the ABAP repository, so it follows a naming convention.ZI_marks a customer-namespace interface view (see the next chapter). - The data source.
as select from zcustomernames a table or another CDS view. - The element list in braces. It lists the fields to expose.
keymarks the fields that make a row unique.as CustomerIdgives each field an alias, so the view exposes business-friendly camel-case names instead of technical column names.
Annotations placed before an element, like @Semantics.text: true, describe that single element. Here it tells consumers that CustomerName is the text for the key.
Keys
A view entity needs a key, and the key must be unique per row. Analytical engines rely on it. If your key does not identify rows uniquely, results can change depending on how the database happens to read the data. For a table with a composite key, mark every key field with key.
Common view features
A view entity can do more than rename fields. These features appear often in analytical models:
| Feature | Example | Use |
|---|---|---|
| Aliasing | `country as Country` | Readable, stable names |
| Casting | `cast( amount as abap.curr(15,2) )` | Set the data type of an element |
| Calculated field | `quantity * price as GrossValue` | Derive values in the view |
| Case expression | `case when status = 'A' then 'Open' else 'Closed' end` | Map codes to categories |
| Filter | `where country <> ''` | Restrict the rows |
| Join | `inner join`, `left outer join` | Combine sources in the same SELECT |
| Association | `association [0..1] to ...` | Declare a reusable relationship |
You can write all of these with the plain-SQL knowledge you already have. Associations are the one feature with no direct SQL equivalent, so the rest of this chapter focuses on them.
Associations
An association is a named, reusable relationship from one view to another. It defines the join condition once and gives it a name. The join is not executed unless a consumer uses the association.
The cube view in the running example declares one:
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Sales item cube'
@Analytics.dataCategory: #CUBE
define view entity ZI_SalesItemCube
as select from zsales_item
association [0..1] to ZI_CustomerDim as _Customer
on $projection.CustomerId = _Customer.CustomerId
{
key item_uuid as ItemUuid,
@ObjectModel.foreignKey.association: '_Customer'
customer_id as CustomerId,
@Semantics.currencyCode: true
currency as Currency,
@DefaultAggregation: #SUM
@Semantics.amount.currencyCode: 'Currency'
net_amount as NetAmount,
_Customer
}Read the association line piece by piece:
association [0..1] to ZI_CustomerDim as _Customerdeclares a relationship to the dimension view and names it_Customer. By convention, association names start with an underscore.[0..1]is the cardinality. Each sales item has at most one customer. The first number is the minimum of target rows per source row. The second is the maximum.on $projection.CustomerId = _Customer.CustomerIdis the join condition.$projectionrefers to an element in this view's own element list, by its alias. Using$projectionkeeps the condition tied to the exposed name, not to the table column.- Listing
_Customerin the element list exposes the association. Consumers can then navigate through it, and view-level metadata can refer to it.
Cardinality
Cardinality describes the relationship and affects how the database can optimise the join.
| Notation | Meaning | Typical case |
|---|---|---|
| `[0..1]` | Zero or one target row | Optional master data, such as a customer that may be missing |
| `[1]` | Exactly one target row | Mandatory master data with enforced integrity |
| `[0..*]` | Zero or many target rows | A header with its items |
| `[1..*]` | At least one target row | A header that always has items |
Declare the real cardinality. If you declare [0..1] but the target can return two rows for one source row, results in the analytical query are duplicated, and amounts are counted twice. The system does not check this against your data. For a dimension keyed by its ID, [0..1] is the safe default for a left outer join semantics.
How associations are evaluated
A consumer can use an association in three ways:
- Path expression in a select list. A view that reads from
ZI_SalesItemCubecan select_Customer.CountryNameor_Customer.Country. The system generates a left outer join to the target only for the paths that are used. - Path expression in a filter or condition. The same rule applies in
whereclauses. - Navigation by a front end. Analytical tools follow the exposed association to reach dimension attributes and texts. The
@ObjectModel.foreignKey.associationannotation onCustomerIdtells them that this field is a foreign key to_Customer.
If no consumer uses the association, the database never joins the target table. This is the main reason to prefer associations over fixed joins when building a reusable model. A cube can expose many dimension associations, and a query that needs two of them pays for two joins.
Association or join?
Both are valid, and the choice depends on what you are modelling.
| Criterion | Association | Join |
|---|---|---|
| Executed when | A consumer uses a path to it | Always, on every read |
| Reuse | Declared once, usable by every consumer | Fixed inside this one view |
| Can change the number of rows | No, when the cardinality is correct (left outer semantics) | Yes, an inner join removes rows and a one-to-many join multiplies them |
| Best for | Master data, texts, navigation to related objects | Combining data that every row of the view needs, or filtering rows by existence |
Use an association when the target is optional context for a row, such as a customer, a product or a text. Use a join when the data is part of the row's definition, or when you must drop rows that have no match.
Reading a view during development
You can check a view quickly in ADT. Open the data definition and choose Open With > Data Preview. The preview runs the view against the database. Associations that you expose appear as links you can follow. If you see more rows than expected, suspect a wrong key or a wrong cardinality before looking anywhere else.
Common errors
- Wrong cardinality. The system accepts
[0..1]on a relationship that returns several rows. The symptom is inflated totals later, not an error message now. - Missing key or non-unique key. Rows collapse or repeat in unpredictable ways. Check that the
keyfields identify each row. - Association defined but not exposed. If you forget to list
_Customerin the element list, consumers cannot navigate to it. Annotations that name it, such as the foreign key annotation, then point to something that is not visible. - Using the table column in the ON condition. Write
$projection.CustomerId, notcustomer_id, when the element is aliased. The condition then follows the exposed name. - Mixing up view entity and DDIC-based view syntax.
define view entitydoes not take@AbapCatalog.sqlViewName. Adding it causes a syntax error. - Authorization annotation set carelessly.
#NOT_REQUIREDon a view with sensitive data skips row-level checks. The dimension above uses it because the data is general master data. The cube uses#CHECK, which expects an access control. Authorizations are covered in a later chapter.
Where this leads
You now have the two ingredients every analytical model uses: a view entity that exposes keyed, aliased elements, and associations that link views without forcing a join. The next chapter arranges such views into the layers of the Virtual Data Model. Later chapters add the analytical annotations that turn these views into cubes, dimensions and queries.
Exercise
A view ZI_SalesItemCube declares association [0..1] to ZI_CustomerDim as _Customer and exposes _Customer in its element list. A query reads only ItemUuid and NetAmount from the cube and never uses _Customer. Does the database read the table zcustomer? Then, a colleague changes the association to [0..1] while the dimension can really return two rows per customer ID. What goes wrong?
Show answer
No. The association is joined only when a consumer uses a path to it, so zcustomer is not read. In the second case, a query that does use _Customer joins two target rows to each sales item, so each item appears twice and NetAmount is summed twice. The system does not check cardinality against the data, so the wrong total shows up with no error message.
Exercise
You need a view that lists sales items together with the product description, and you must return only items that have a product. Should you use an association or a join, and why?
Show answer
Use a join, specifically an inner join. The requirement to drop items without a product is a filter on existence, and a join applies it on every read. An association with left outer semantics would keep items that have no product.