英文原文:SAP-samples · 上游版本 d43eb13c4c7c · 原始 Markdown
ABAP for RAP: Entity Manipulation Language (ABAP EML)
- ABAP for RAP: Entity Manipulation Language (ABAP EML)
- RAP Terms
- RAP Behavior Definition (BDEF)
- ABAP Behavior Pools (ABP)
- BDEF Derived Types
- ABAP EML Syntax
- ABAP EML Syntax for Modifying Operations
- ABAP EML Syntax for Reading Operations
- COMMIT ENTITIES: Persisting to the Database
- ROLLBACK ENTITIES
- GET PERMISSIONS: Retrieving Information about RAP BO Permissions
- SET LOCKS: Exclusively Locking Instances
- Raising RAP Business Events
- Additions to ABAP EML Statements in ABAP Behavior Pools
- RAP Excursions
- More Information
- Executable Examples
RAP Terms
ABAP Entity Manipulation Language (or EML for short) is a subset of ABAP that allows you to access the data of RAP business objects in an ABAP program. The following points cover RAP-related terms such as RAP business objects and others for setting the context:
| Terms | Notes |
|
RAP business objects (RAP BO) |
|
|
RAP behavior definition (BDEF) |
|
|
Transactional buffer and implementation types |
|
|
Managed RAP BOs |
|
|
Unmanaged RAP BOs |
|
|
ABAP behavior implementation in an ABAP behavior pool (ABP) |
|
[!NOTE]
- Find more terms in the RAP Glossary of the ABAP Keyword Documentation.
- There are more artifacts and concepts related to RAP that go way beyond the scope of this cheat sheet. For example, a RAP BO can be exposed as a business service to be accessed from outside AS ABAP and consumed. A RAP BO consumer is either the RAP transactional engine that handles requests from outside the AS ABAP or, from inside AS ABAP, an ABAP program using ABAP EML (which this cheat sheet and the examples focus on).
- The cheat sheet and the examples focus on a minimal number of artifacts - from database table and view entity, to BDEF and ABAP behavior pool, including an ABAP class as consumer. Many other RAP-related artifacts and aspects are beyond the scope. Get a more thorough insight in the Development guide for the ABAP RESTful Application Programming Model.
- You can create all RAP service-related repository objects from scratch using a wizard in ADT. The wizard lets you manually input your RAP BO requirements or use the Joule chat. Find more information here.
RAP Behavior Definition (BDEF)
- As the name implies, a RAP behavior definition describes a RAP business object (RAP BO) by defining its behavior for all of its RAP BO entities.
- BDL source code is used in a BDEF.
- Once you have created ...
- the CDS root entity of a RAP BO, ADT helps you create the skeleton of a BDEF (e.g., right-click on the CDS root entity and choose New Behavior Definition from the pop-up).
- the BDEF, ADT helps you create the skeleton of an ABAP behavior pool, as well as RAP handler and saver method declarations and the skeleton of implementations via ADT quick fixes.
- Find more information in the RAP Behavior Definition Language cheat sheet.
ABAP Behavior Pools (ABP)
You can access RAP BO data from inside AS ABAP using EML. Among other things, EML allows you to read or modify RAP BOs by accessing the RAP BO data (the RAP BO instances) in the transactional buffer and trigger the persistent storage or reset changes. More precisely, when EML statements are executed, the calling of RAP handler methods is triggered to access the transactional buffer of a RAP BO. As mentioned, for unmanaged RAP BOs or unmanaged parts of managed RAP BOs, the handler methods that are called are part of an ABAP behavior pool.
The global class of an ABP has the addition FOR BEHAVIOR OF bdef
to the definition while bdef stands for the name of the BDEF.
This class is (initially) empty apart from the declaration and implementation part skeleton.
CLASS zbp_demo_abap_rap_draft_m DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zdemo_abap_rap_draft_m.
ENDCLASS.
CLASS zbp_demo_abap_rap_draft_m IMPLEMENTATION.
ENDCLASS.
The actual implementation is done in local classes in the CCIMP include (Local Types tab in ADT) of the behavior pool. There, two kinds of local classes are to be defined and implemented that are related to the RAP BO's runtime: one or more handler classes to implement the RAP BO behavior (in RAP handler methods) during the RAP interaction phase (the data reading and modification phase) and a saver class to implement the RAP save sequence (in saver methods to save data from the transactional buffer to the database).
RAP Handler Classes and Methods
- One or more handler classes implement the RAP interaction phase. For modularization purposes, one behavior pool can define multiple handler classes. For example, each entity can have its own handler class, or individual handler classes can be defined to distinguish between reading and changing RAP BO entities.
- A handler class inherits from class
CL_ABAP_BEHAVIOR_HANDLER. - These classes are implicitly
ABSTRACTandFINALsince instantiating and calling only happens through the RAP runtime engine. - ADT helps you create the classes and methods (and basically the ABP as such) when creating the BDEF. A quick fix is available that creates the method definitions and a skeleton of the implementations automatically.
Example: Handler class definition
CLASS lhc_root DEFINITION INHERITING FROM cl_abap_behavior_handler.
...
ENDCLASS.
- Handler method definitions include the additions
... FOR ... FOR ...followed by the kinds of operations. There are various options depending on the RAP BO operation. - Depending on the definition in the BDEF, there might be more additions
with dedicated method parameters. For example, an action might
be defined with a result parameter, hence, the method must be
defined with the addition
RESULTand a parameter. - The
FOR MODIFYhandler method can handle multiple entities and operations, i. e. not only create but also update or delete might be integrated in the method definition. However, it might be useful to split the handler method into separate methods for better readability. - See more details on the handler method definitions in the topic
METHODS, FOR.
Example: Handler method definitions
"Create
METHODS create FOR MODIFY
IMPORTING entities FOR CREATE bdef.
"Read: Specifying a read result is mandatory.
METHODS read FOR READ
IMPORTING keys FOR READ bdef RESULT result.
"Action: action name is preceded by the BDEF name and a tilde after FOR ACTION
METHODS some_action FOR MODIFY
IMPORTING keys FOR ACTION bdef~some_action.
Parameters of Handler Methods
- The handler method definitions contain RAP-specific additions like
FOR MODIFY,FOR CREATEorFOR READas well as mandatory or optional additions likeRESULTthat are followed by parameters. - The parameters are typed with BDEF derived types that have special RAP-related components as covered further down.
- The parameters' names can be chosen freely. This is also true for the method names except for some predefined names.
- Each handler method must have at least one importing parameter.
Specifying the addition
IMPORTINGexplicitly is optional since it is used implicitly. In most cases, entire instances or just key values of instances are imported. - All handler methods have changing parameters that are usually not
explicitly specified in the definition but implicitly used. The
explicit specification of the
CHANGINGaddition is not needed. In most cases, these are RAP response parameters. The following image shows the F2 information in ADT for the create handler method.
- The response parameters
mapped,failedandreported(the names are predefined) can be considered as containers for information - information a RAP BO consumer is provided with by a RAP BO provider, for example, an SAP Fiori app displays an error message if something went wrong. The availability of the parameters depends on the handler method used (e. g.mappedis only available for operations creating instances).mapped: Used to provide mapping information on RAP BO instances, for example, which key values were created for given content IDs (%cid).failed: Information for identifying the data set for which an error occurred in a RAP operationreported: Used, for example, to exchange error messages for each entity defined in the BDEF and not related to a specific entity.- Example: Technically, the
reportedparameter is a deep structure containing, for example, the messages of the root entity and child entities. For example, if a create operation fails for a RAP BO instance of the root entity, a message, information about the instance key and other things can be included in this parameter which is passed to a RAP BO consumer. You could imagine that such an error message is displayed on an SAP Fiori UI if something goes wrong to inform the user.
[!NOTE]
It is essential to implement RAP handler methods correctly to ensure the stability and consistency of RAP business objects, particularly in populating the RAP response parameters. For more details on best practices for implementation, refer to the documentation.
RAP Saver Class and Saver Methods
- A RAP saver class implements the RAP save sequence. A saver class is usually only available in unmanaged RAP BOs (except for special variants of managed RAP BOs that are not outlined here).
- The saver class is implicitly
ABSTRACTandFINALsince the instantiating and calling only happens through the RAP runtime engine. - A saver class can be defined in the CCIMP include (Local Types tab in ADT) of an ABAP behavior pool. It includes the definitions and implementations of RAP saver methods.
- The saver methods consist of a set of predefined methods having
predefined names. Some of them are mandatory to implement, some are
optional. The
adjust_numbersmethod is only available in late numbering scenarios. - A saver class inherits from class
CL_ABAP_BEHAVIOR_SAVER. The saver methods are declared by redefining predefined methods of the superclass. They implicitly have response parameters. - In contrast to RAP handler methods, saver methods do not have data of RAP BO instances as import parameter. Therefore, instance data must be handled via the transactional buffer when self-implementing the saver methods.
- Saver methods are called when the RAP save sequence has been triggered by a
COMMIT ENTITIESstatement. Note that in natively supported RAP scenarios, for example, an SAP Fiori app using OData, theCOMMIT ENTITIEScall is performed implicitly and automatically by the RAP runtime engine. - Find more information on RAP saver methods here.
Example: Definition of a RAP saver class and saver methods
CLASS lsc_bdef DEFINITION INHERITING FROM cl_abap_behavior_saver.
PROTECTED SECTION.
"For final calculations and data modifications involving all
"BOs in the current RAP transaction
METHODS finalize REDEFINITION.
"Checks the consistency of the transactional buffer before
"the save method saves data to the database
METHODS check_before_save REDEFINITION.
"Preliminary IDs are mapped to final keys. Only for late numbering.
METHODS adjust_numbers REDEFINITION.
"Saves the current state of the transactional buffer to the database
METHODS save REDEFINITION.
"Clear the transactional buffer
METHODS cleanup REDEFINITION.
METHODS cleanup_finalize REDEFINITION.
ENDCLASS.
ABP Auxiliary Classes
- You can optionally define auxiliary classes for ABPs using the syntax
... FOR BEHAVIOR OF bdef_name .... - These classes are implicitly final global classes and reference a RAP business object.
- They have enhanced access rights to RAP BOs, and ABAP EML statements with the
IN LOCAL MODEandPRIVILEGEDcan be used. - Their main function is to support implementation in an ABAP behavior pool. They achieve this by offering reusable methods and enabling developers to implement RAP behavior simultaneously. Furthermore, they can be used to provide utility methods for raising RAP business events.
- Note that RAP handler, saver, and event handler methods as such can only be implemented in a behavior pool, but they can delegate tasks to methods in ABP auxiliary classes. It is not recommended to completely outsource the handler and saver method implementations to auxiliary classes to prevent unnecessary overhead.
- As a prerequisite, the ABAP auxiliary class name is specified in the BDEF using the
auxiliary class ...notation. Multiple ABAP auxiliary classes can be specified.
BDEF Derived Types
The operands of EML statements and parameters of handler and saver methods are mainly special messenger tables for passing data and receiving results or messages, i. e. the communication between a RAP BO consumer and the RAP BO provider using EML consists (in most cases) of exchanging data stored in internal tables that have special ABAP types - BDEF derived types. These types are tailor-made for RAP purposes.
As the name implies, the types are derived by the ABAP runtime framework from CDS entities and their behavior definition in the BDEF. With these special types, a type-safe access to RAP BOs is guaranteed.
[!NOTE]
- To explore BDEF derived types in your RAP BO, you can access the CCIMP include (Local Types tab in ADT) of your ABAP behavior pool, position the cursor on the methods, choose F2 and check the parameters typed with BDEF derived types.
- As mentioned, CRUD operations are implicitly supported in managed scenarios (when specified in the BDEF). So, there will not be method declarations and implementations for CRUD operation methods.
BDEF Derived Type Syntax and Declaring Data Types and Data Objects
-
For all operations and behavior characteristics defined in the BDEF, you can derive types. For example, if you enable create operations (using the
createspecification in the BDEF), you can create respective BDEF derived types. If you do not enable delete operations, you cannot create respective types. -
The syntax, similar to method definitions mentioned earlier, uses the addition
FORfollowed by further RAP-related additions (such asCREATEfor create operations). -
These additions include the name of an entity and, if necessary, a specific name (e.g., the action name for a BDEF derived type related to an action).
-
The following syntax options are available in the context of BDEF derived types:
Syntax Notes TYPE TABLE FORFor creating internal tables with BDEF derived types. Most RAP handler method parameters use tabular BDEF derived types. TYPE STRUCTURE FORIn many cases, structures of type TYPE STRUCTURE FORserve as both the work area and the line type of the internal tables. There are also structured BDEF derived types that function as types for RAP handler method parameters.TYPE RESPONSE FORThese types refer to the RAP response parameters mapped,failed, andreported. They are deep structures containing information for individual RAP BO entities. The components of these structures are internal tables of appropriate types withTYPE TABLE FOR.TYPE REQUEST FORThe types TYPE REQUEST FOR CHANGEandTYPE REQUEST FOR DELETEare relevant for importing parameters of thesave_modifiedRAP saver method in the context of RAP additional and unmanaged save. These BDEF derived types are deep structures containing internal tables with RAP BO instance keys and/or data for create, update, or delete operations. -
Find an overview of available BDEF derived types here.
-
You can use
TYPESandDATAstatements to declare data types and objects with BDEF derived types. -
Both long and short forms are available to declare data types and objects. Example:
- Create an internal table typed with a BDEF derived type for create operations in ADT:
DATA d1 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m. - Position the cursor on
d1and press F2 to get type information. The long form shows the root entity plus the concrete entity (which is the root entity itself, an alias name is specified for the root entity in the example):d1 type table for create zdemo_abap_rap_ro_m\\root.
- Create an internal table typed with a BDEF derived type for create operations in ADT:
-
The following specification options are available:
- Long form: Specifying the name of the RAP BO root entity followed by
\\and an entity of the composition tree.- If an alias is defined for the entity, you must specify it; otherwise, you can specify the entity name.
- If no alias name was specified for the example entity, the long form would be:
DATA d2 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\\zdemo_abap_rap_ro_m.
- Short form: For convenience, you can specify RAP BO entities such as the RAP BO root entity or other CDS entities of a CDS composition tree. Examples:
DATA d1 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.(root entity),DATA d3 TYPE TABLE FOR UPDATE zdemo_abap_rap_ch_m.(child entity). Note that most example codes in the cheat sheet and in the executable example use the short form. - Specifying associations defined in a BDEF preceded by
\: For example,DATA d4 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\_child.. The long form with\\followed by an entity name,\, and an association is also possible.
- Long form: Specifying the name of the RAP BO root entity followed by
[!NOTE]
Certain types derived from the BDEF can only be specified and used within implementation classes, not beyond. These types include the following:FOR CHANGE,FOR DETERMINATION,FOR VALIDATION,FOR ... FEATURES,FOR ... AUTHORIZATION.
BDEF derived type examples:
[!NOTE]
The demo BDEFzdemo_abap_rap_ro_m...
- specifies the alias name
rootfor the RAP BO root entityzdemo_abap_rap_ro_m.- specifies the association
_child.- includes the child entity
zdemo_abap_rap_ch_m, for which an alias namechildis specified and which specifies the association_parent.
*&---------------------------------------------------------------------*
*& BDEF derived types demonstrating long and short forms
*&---------------------------------------------------------------------*
"Short forms
"Specifying the RAP BO root entity
TYPES t1 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
DATA d1 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
"Specifying child entity
TYPES t2 TYPE TABLE FOR UPDATE zdemo_abap_rap_ch_m.
DATA d2 TYPE TABLE FOR UPDATE zdemo_abap_rap_ch_m.
"Long form: Specifying the name of the RAP BO root entity, followed
"by \\ and an entity of the composition tree
"Since an alias name is specified for the example entities, it must
"be specified after \\. Otherwise, the entity name can be specified.
"t3/d3 are the same as t1/d1.
TYPES t3 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\\root.
DATA d3 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\\root.
"In this example, t4/d4 are the same as t2/d2.
TYPES t4 TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m\\child.
DATA d4 TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m\\child.
"Specifying associations that are declared in the BDEF preceded by \
"with both short and long forms
"In this example, t5/d5 are the same as t6/d6.
TYPES t5 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\_child.
DATA d5 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\_child.
TYPES t6 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\\root\_child.
DATA d6 TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\\root\_child.
"In this example, t7/d7 are the same as t8/d8.
TYPES t7 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\\child\_parent.
DATA d7 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\\child\_parent.
TYPES t8 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ch_m\_parent.
DATA d8 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ch_m\_parent.
*&---------------------------------------------------------------------*
*& Miscellaneous BDEF derived types
*&---------------------------------------------------------------------*
"The examples show a selection of possible types. The types mostly use
"the short form.
*&---------------------------------------------------------------------*
*& Table types
*&---------------------------------------------------------------------*
"Create
DATA create_tab TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
"Update
DATA update_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m.
"Create-by-association operation specifying the name of the entity
"and the association
DATA cba_tab TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\_child.
"Action; the name of the action is preceded by a tilde
DATA action_import TYPE TABLE FOR ACTION IMPORT zdemo_abap_rap_ro_m~multiply_by_2.
"The example action does not specify a result parameter, therefore the following
"type is not available.
"DATA action_result TYPE TABLE FOR ACTION RESULT zdemo_abap_rap_ro_m~multiply_by_2.
"Read
DATA read_import TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m.
DATA read_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m.
"The previous examples use the RAP BO root entity. The following ones
"use a child entity specified in the example BDEF.
"Update
DATA update_tab_ch TYPE TABLE FOR UPDATE zdemo_abap_rap_ch_m.
"Which corresponds to the long form sepcifying the RAP BO root entity
"name and the (alias) name of the child entity followed by \\
DATA update_tab_ch_2 TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m\\child.
DATA delete_tab_ch TYPE TABLE FOR DELETE zdemo_abap_rap_ch_m.
"Read-by-association
DATA rba_import_child_to_parent TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ch_m\_parent.
DATA rba_import_child_to_parent_2 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\\child\_parent.
DATA rba_result_child_to_parent TYPE TABLE FOR READ RESULT zdemo_abap_rap_ch_m\_parent.
DATA rba_result_child_to_parent_2 TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\\child\_parent.
*&---------------------------------------------------------------------*
*& Structured types
*&---------------------------------------------------------------------*
DATA create_wa TYPE STRUCTURE FOR CREATE zdemo_abap_rap_ro_m.
DATA update_wa TYPE STRUCTURE FOR UPDATE zdemo_abap_rap_ro_m.
TYPES delete_wa TYPE STRUCTURE FOR DELETE zdemo_abap_rap_ro_m.
DATA update_child_wa TYPE STRUCTURE FOR UPDATE zdemo_abap_rap_ch_m.
TYPES delete_child_wa TYPE STRUCTURE FOR DELETE zdemo_abap_rap_ch_m.
"Retrieving permissions
DATA perm_req TYPE STRUCTURE FOR PERMISSIONS REQUEST zdemo_abap_rap_ro_m.
"Retrieving global features
"... FOR ... FEATURES ... can only be used within implementation classes
"DATA feat_req TYPE STRUCTURE FOR GLOBAL FEATURES RESULT zdemo_abap_rap_ro_m.
"The same applies to validations and determinations
"DATA validate TYPE TABLE FOR VALIDATION zdemo_abap_rap_ro_m~val.
"DATA determine TYPE TABLE FOR DETERMINATION zdemo_abap_rap_ro_m~det_add_text.
*&---------------------------------------------------------------------*
*& BDEF derived types relating to RAP response parameters
*&---------------------------------------------------------------------*
"Response parameters
"Note: The addition EARLY or no addition is relevant in the context of the
"RAP interaction phase. The addition LATE is relevant in the context of the
"save phase.
DATA map TYPE RESPONSE FOR MAPPED zdemo_abap_rap_ro_m.
DATA fail TYPE RESPONSE FOR FAILED zdemo_abap_rap_ro_m.
DATA resp TYPE RESPONSE FOR REPORTED zdemo_abap_rap_ro_m.
"Same as resp
DATA resp_2 TYPE RESPONSE FOR REPORTED EARLY zdemo_abap_rap_ro_m.
"Relevant for the late RAP save phase
DATA map_late TYPE RESPONSE FOR MAPPED LATE zdemo_abap_rap_ro_m.
DATA fail_late TYPE RESPONSE FOR FAILED LATE zdemo_abap_rap_ro_m.
DATA resp_late TYPE RESPONSE FOR REPORTED LATE zdemo_abap_rap_ro_m.
"You can check the F2 information in ADT for the types. The types above
"are deep structures, containing tables typed with TYPE TABLE FOR MAPPED
"and so on.
DATA map_tab_early_1 TYPE TABLE FOR MAPPED zdemo_abap_rap_ro_m.
DATA map_tab_early_2 TYPE TABLE FOR MAPPED EARLY zdemo_abap_rap_ro_m.
DATA map_tab_late TYPE TABLE FOR MAPPED LATE zdemo_abap_rap_ro_m.
*&---------------------------------------------------------------------*
*& BDEF derived types relating to the save phase in RAP additional
*& and unmanaged save scenarios
*&---------------------------------------------------------------------*
"REQUEST FOR ... can only be used within implementation classes
"For create and update operations
"DATA req_change TYPE REQUEST FOR CHANGE zdemo_abap_rap_ro_m_as.
"For delete operations
"DATA req_delete TYPE REQUEST FOR DELETE zdemo_abap_rap_ro_m_as.
*&---------------------------------------------------------------------*
*& Excursion: Typing method parameters with BDEF derived types
*&---------------------------------------------------------------------*
"TYPES tab_type TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
"METHODS some_meth IMPORTING itab TYPE tab_type.
Components of BDEF Derived Types
Many of the BDEF derived types contain components of CDS entities like
key and data fields that retain their original data type, for example, a
messenger table typed with TYPE TABLE FOR CREATE. Certainly,
if an instance is to be created, key and field values of a RAP BO
instance are of relevance.
Yet, all BDEF derived types contain special RAP components serving a
dedicated purpose. The names of these RAP components begin with
% to avoid naming conflicts with components of the CDS
entities. The following image shows the F2 information of a BDEF derived
type containing the % components and fields from the CDS
entity.

Some of the % components are component
groups
summarizing groups of table columns under a single name. In doing so,
they simplify the handling of derived types for developers. For example,
the component group
%data
contains all primary key and data fields of a RAP BO entity (actually,
by containing the keys, it also contains the component group
%key
in the case above). The F2 information in ADT helps you find out about
the available components in a variable. The image below shows the
details of %data when clicking the derived type
link in the first ADT F2 information screen.

The availability of % components depends on definitions in the
BDEF. Their availability also depends on more criteria, for example, the
scenario. For example, the component
%pid
that represents a preliminary ID for a RAP BO instance is only available
in late
numbering
scenarios. The draft indicator
%is_draft
is only relevant in the context of
draft.
The following table covers a selection of available BDEF derived type components. Find more details on the available components in section Components of BDEF Derived Types of the ABAP Keyword Documentation.
| Component | Notes | Code Snippet |
|---|---|---|
|
|
|
|
The code snippet visualizes various specification options regarding
|
|
|
|
|
|
|
|
|
|
The following code snippet illustrates the importance of careful component access and value assignment with component groups in BDEF derived types:
- It uses the key component of a demo RAP BO and an internal table of type
FOR CREATEas an example. - The type includes the component groups
%dataand%key. %datacontains%keyas a component.- Component access may be done in various ways.
- Especially in value assignments, make sure that there is only one assignment per component.
DATA cr_tab TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
cr_tab = VALUE #( ( key_field = 1 ) ).
DATA(a) = cr_tab[ 1 ]-key_field.
DATA(b) = cr_tab[ 1 ]-%key-key_field.
DATA(c) = cr_tab[ 1 ]-%data-key_field.
DATA(d) = cr_tab[ 1 ]-%data-%key-key_field.
"Even more specification options with another BDEF derived type.
"This is only to visualize the variety of component groups in BDEF
"derived types.
DATA upd_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m.
upd_tab = VALUE #( ( key_field = 1 ) ).
DATA(e) = upd_tab[ 1 ]-key_field.
DATA(f) = upd_tab[ 1 ]-%key-key_field.
DATA(g) = upd_tab[ 1 ]-%tky-%key-key_field.
DATA(h) = upd_tab[ 1 ]-%tky-key_field.
DATA(i) = upd_tab[ 1 ]-%tky-%pky-%key-key_field.
DATA(j) = upd_tab[ 1 ]-%tky-%pky-key_field.
DATA(k) = upd_tab[ 1 ]-%pky-key_field.
DATA(l) = upd_tab[ 1 ]-%pky-%key-key_field.
DATA(m) = upd_tab[ 1 ]-%data-%key-key_field.
DATA(o) = upd_tab[ 1 ]-%data-key_field.
Constants for BDEF Derived Type Components
Several BDEF derived types contain % components, which have a specific type and represent flags. The mentioned %control structure, whose components are of type ABP_BEHV_FLAG, is such a component. When assigning values to these components, ensure you use appropriate values. The IF_ABAP_BEHV interface provides a range of structured constants for this purpose. Although these constants are technically identical, it is recommended that you use them in the right context.
| Type | Structured Constant | Details |
|---|---|---|
ABP_BEHV_FLAG |
IF_ABAP_BEHV=>MK |
Marks and unmarks fields in ABAP EML modify and read operations, such as in %control and %element. |
ABP_BEHV_FIELD_PERM |
IF_ABAP_BEHV=>PERM-F |
Used in the context of field permission results, such as a field marked as mandatory or read-only. |
ABP_BEHV_OP_PERM |
IF_ABAP_BEHV=>PERM-O |
For operation permission results, such as a delete operation that is marked as enabled. |
ABP_BEHV_FIELD_CTRL |
IF_ABAP_BEHV=>FC-F |
For field feature control results, such as a field marked with no restrictions. |
ABP_BEHV_OP_CTRL |
IF_ABAP_BEHV=>FC-O |
For operation feature control results, such as a disabled update operation. |
ABP_BEHV_AUTH |
IF_ABAP_BEHV=>AUTH |
For authorization results, such as an unauthorized operation. |
IF_ABAP_BEHV=>T_CHAR01 |
IF_ABAP_BEHV=>OP |
For dynamic ABAP EML statements; e.g. if_abap_behv=>op-m-create for create and if_abap_behv=>op-r-read for read operations. |
IF_ABAP_BEHV=>T_CHAR01 |
IF_ABAP_BEHV=>COP |
For accumulated change operation information such as in the context of draft additional save; e.g. if_abap_behv=>cop-update for update operations. |
Secondary Table Keys of BDEF Derived Types
- Internal tables typed with BDEF derived types (
TYPE TABLE FOR ...) are standard tables with an empty primary table key (primary_key). - Predefined secondary table keys are available for many types.
- These secondary table keys are always sorted keys.
- Currently available secondary table keys (as also visible in one of the images above when using the F2 help in ADT):
entity: Includes%keycid: Includes%cidor%cid_ref, and can - depending on the type - also include%keyand%piddraft: Available in draft scenarios; includes%is_draft; can also include%keyand%pidpid: Available in late numbering scenarios; includes%pid; can also include%tmpand%key- The alias name
idis available for eitherentity,draft, orpiddepending on the context. Check the F2 information in ADT for the respective types.
DATA itab_cr TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m.
itab_cr = VALUE #( %control-key_field = if_abap_behv=>mk-on
%control-field1 = if_abap_behv=>mk-on
%control-field2 = if_abap_behv=>mk-on
%control-field3 = if_abap_behv=>mk-on
%control-field4 = if_abap_behv=>mk-on
( %cid = `cid1`
%key-key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 11
field4 = 111 ) ).
"Secondary table keys available in the example table: cid, entity
"The statements demonstrate the secondary table keys using table expressions.
"The statements commented out raise a syntax warning. The secondary table key
"should be specified explicitly.
"DATA(line_a) = itab_cr[ %cid = `cid1` ].
"DATA(line_b) = itab_cr[ %cid = `cid1` %key = VALUE #( key_field = 1 ) ].
DATA(line_c) = itab_cr[ KEY cid COMPONENTS %cid = `cid1`
%key = VALUE #( key_field = 1 ) ].
"DATA(line_d) = itab_cr[ %key = VALUE #( key_field = 1 ) ].
"The COMPONENTS addition is optional.
DATA(line_e) = itab_cr[ KEY entity %key = VALUE #( key_field = 1 ) ].
Type Mapping for RAP
RAP-Specific Additions to the CORRESPONDING Operator
The CORRESPONDING operator offers RAP-specific additions for handling type mappings related to BDEF derived types and other types. For more information, see the ABAP Keyword Documentation topic.
The following additions are available:
... CORRESPONDING ...( ... MAPPING FROM ENTITY ) ...
... CORRESPONDING ...( ... MAPPING TO ENTITY ) ...
... CORRESPONDING ...( ... USING CONTROL ) ...
... CORRESPONDING ...( ... MAPPING FROM ENTITY USING CONTROL ) ...
... CORRESPONDING ...( ... CHANGING CONTROL ) ...
For some additions, a mapping needs to be specified in the BDEF. For more information, see the
ABAP Keyword Documentation topic.
The following example uses a BDEF derived type from the ABAP cheat sheets. It shows additions that do not require a type mapping to be specified.
"BDEF derived type
DATA derived_type TYPE STRUCTURE FOR UPDATE zdemo_abap_rap_ro_m.
"Other type
"For simplicity, the structure has the same component names
"and types to avoid further additions in the statement.
DATA: BEGIN OF some_other_type,
key_field TYPE i,
field1 TYPE c LENGTH 10,
field2 TYPE c LENGTH 10,
field3 TYPE i,
field4 TYPE i,
END OF some_other_type.
derived_type = VALUE #( key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 2
field4 = 3
%control = VALUE #( key_field = if_abap_behv=>mk-on
field1 = if_abap_behv=>mk-off
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-off ) ).
*&---------------------------------------------------------------------*
*& USING CONTROL addition
*&---------------------------------------------------------------------*
"This addition respects the %control component of BDEF derived types, i.e.
"only those fields for which the %control field has been marked as enabled
"are respected by the mapping. A disabled %control field means that the
"mapping is not applied.
"In the example, components are marked as disabled in %control.
"Consequently, the field values are not assigned, and the type-specific
"initial values are used.
some_other_type = CORRESPONDING #( derived_type USING CONTROL ).
*KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4
*1 bbb 2 0
*&---------------------------------------------------------------------*
*& CHANGING CONTROL addition
*&---------------------------------------------------------------------*
"This variant fills the %control structure of a BDEF-derived type based on
"a non-BDEF-derived type that does not include control information.
"In the example, two components are not assigned (i.e. they remain initial).
"Consequently, when using the CORRESPONDING operator with CHANGING CONTROL,
"the %control values are marked as disabled, the others as enabled.
some_other_type = VALUE #( key_field = 4 field1 = 'ccc' field4 = 5 ).
derived_type = CORRESPONDING #( some_other_type CHANGING CONTROL ).
*%CID_REF KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4 %CONTROL
* 4 ccc 0 5 KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4
* 01 01 00 00 01
ABAP SQL Statements with BDEF Derived Types
The ABAP SQL statements INSERT, UPDATE, MODIFY, and DELETE offer the MAPPING FROM ENTITY addition to handle BDEF derived types.
*&---------------------------------------------------------------------*
*& INSERT
*&---------------------------------------------------------------------*
"Populating a BDEF derived type
DATA cr_der_type TYPE STRUCTURE FOR CREATE zdemo_abap_rap_ro_m.
"%control is not relevant in this example
cr_der_type = VALUE #( key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 2
field4 = 3 ).
INSERT zdemo_abap_rapt1 FROM @cr_der_type MAPPING FROM ENTITY.
*KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4
*1 aaa bbb 2 3
*&---------------------------------------------------------------------*
*& MODIFY
*&---------------------------------------------------------------------*
cr_der_type = VALUE #( BASE cr_der_type
field1 = 'YYY'
field2 = 'ZZZ' ).
MODIFY zdemo_abap_rapt1 FROM @cr_der_type MAPPING FROM ENTITY.
*KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4
*1 YYY ZZZ 2 3
*&---------------------------------------------------------------------*
*& UPDATE with the INDICATORS SET STRUCTURE %control addition
*&---------------------------------------------------------------------*
"Populating a BDEF derived type
"%control is relevant in this example. Some %control values are enabled,
"some are not.
cr_der_type = VALUE #( key_field = 1
field1 = '###'
field2 = '...'
field3 = 100
field4 = 200
%control = VALUE #( key_field = if_abap_behv=>mk-on
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-off
field3 = if_abap_behv=>mk-off
field4 = if_abap_behv=>mk-on ) ).
UPDATE zdemo_abap_rapt1 FROM @cr_der_type
INDICATORS SET STRUCTURE %control MAPPING FROM ENTITY.
*KEY_FIELD FIELD1 FIELD2 FIELD3 FIELD4
*1 ### ZZZ 2 200
*&---------------------------------------------------------------------*
*& DELETE
*&---------------------------------------------------------------------*
DELETE zdemo_abap_rapt1 FROM @cr_der_type MAPPING FROM ENTITY.
[!NOTE]
More information and ABAP statements: Type Mapping for RAP
ABAP EML Syntax
The focus is here on selected EML statements. These statements can be fairly long and various additions are possible. Find more information on the EML statements here.
ABAP EML Syntax for Modifying Operations
The modifying operations covered include the standard operations (using
the additions
CREATE,
CREATE BY,
UPDATE,
and
DELETE)
and non-standard operations (actions) using the addition
EXECUTE.
All EML statements for the mentioned operations begin with
MODIFY.
The following commented code snippets demonstrate the
short
and long
form
of EML MODIFY statements.
[!NOTE] Unlike reading operations, modifying operations are not enabled by default. You must make the respective notations in the BDEF:
... create; update; delete; action some_act; ...
Create Operation Using the Short Form of ABAP EML MODIFY Statements
- The following code snippet demonstrates the creation of new instances of a RAP BO entity.
- The short form of the
MODIFYstatement is used. - Note that the statement has multiple (optional) additions.
- The statement uses the
FIELDS ( ... ) WITHaddition. See more details in the documentation and below. - The statements, as is also valid for the following sections, can also use data objects declared and created inline.
"Declaration of data objects using BDEF derived types
DATA: cr_tab TYPE TABLE FOR CREATE root_ent, "input derived type
mapped_resp TYPE RESPONSE FOR MAPPED root_ent, "response parameters
failed_resp TYPE RESPONSE FOR FAILED root_ent,
reported_resp TYPE RESPONSE FOR REPORTED root_ent.
"Input derived type for the EML statement is filled using the VALUE operator
"Assumption: key_field is the key field having type i,
"field1 and field2 are data fields with character-like data type.
"Specify %cid even if not used or of interest; it must be unique within a request
cr_tab = VALUE #(
( %cid = 'cid1' key_field = 1
field1 = 'A' field2 = 'B' )
( %cid = 'cid2'
"Just to demo %data/%key. You can specify fields with or without
"the derived type components
%data = VALUE #( %key-key_field = 2
field1 = 'C'
field2 = 'D' ) ) ).
"EML statement, short form
"root_ent must be the full name of the root entity, it is basically the name of the BDEF
MODIFY ENTITY root_ent
CREATE "determines the kind of operation
FIELDS ( key_field field1 field2 ) WITH cr_tab "Fields to be respected for the
"input derived type and the input
"derived type itself
MAPPED mapped_resp "mapping information
FAILED failed_resp "information on failures with instances
REPORTED reported_resp. "messages
[!NOTE]
- Addition
FIELDS ( ... ) WITH: This field selection option specifies which fields are to be respected for the operation. The derived type, i. e. an internal table containing the concrete RAP BO instance values, followsWITH. If a field is specified in the field list within the pair of parentheses afterFIELDS, the%controlflag for this field is automatically set toif_abap_behv=>mk-on. Likewise, if a field is not contained in the list, the flag in%controlis set toif_abap_behv=>mk-off. Assumefield2is not specified in the list. The value forfield2will not be respected (even if a value is specified in the internal table). The initial value will be used for the field.- Retrieving the responses and specifying the parameters is optional. Assuming a data set with the value 2 for
key_fieldalready exists on the database for this BO, you should expect an entry for this particular instance in thefailed_respoperand and potentially an error message inreported_resp, too. Nevertheless, especially in ABP implementations and depending on the context (in those methods you self-implement), you should implement and fill these parameters according to the RAP BO contract to meet the variety of implementation rules.%cidshould (or rather must) be provided even if you are not interested in its and subsequent operations do not require the reference. For an automatic provision of the%cidvalue, you can use theAUTO FILL CIDaddition in create operations.
Create Operation Using the Long Form of ABAP EML MODIFY Statements
- The example demonstrates the long form of an ABAP EML
MODIFYstatement. - The example statement uses the
FROMaddition instead ofFIELDS ( ... ) WITH. See more details in the documentation and below.
MODIFY ENTITIES OF root_ent "full name of root entity
ENTITY root "root or child entity (alias name if available)
CREATE FROM "FROM as further field selection variant
VALUE #( ( %cid = 'cid' "Input derived type created inline
key_field = 3
field1 = 'E'
field2 = 'F'
%control = VALUE #( "Must be filled when using FROM
key_field = if_abap_behv=>mk-on
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on ) ) )
MAPPED DATA(m) "Target variables declared inline
FAILED DATA(f)
REPORTED DATA(r).
"Note: You can use the AUTO FILL CID addition to fill %cid automatically. It is
"also possible in the short form.
MODIFY ENTITIES OF root_ent
ENTITY root
CREATE AUTO FILL CID WITH
VALUE #( ( key_field = 3
field1 = 'E'
field2 = 'F'
%control = VALUE #(
key_field = if_abap_behv=>mk-on
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on ) ) )
MAPPED DATA(m2)
FAILED DATA(f2)
REPORTED DATA(r2).
[!NOTE]
- The entity specified after
ENTITYcan be either the root entity itself or a child entity. If an alias is defined, the alias should be used.- The addition
FIELDS ( ... ) WITHfrom the previous snippet is basically a shortcut for the additionFROMthat is used here. When usingFROM, the values of the%controlstructure must be specified explicitly.- The BDEF derived types can also be created inline as shown in the example using a constructor expression for the input derived type and with
DATAorFINALfor the responses.- The long form allows you to bundle several operations in one statement, either different operations on the same entity (for example, deleting some instances and updating some others) or operations on different entities of the same RAP BO (for example, creating a root entity instance and related instances of a child entity in one EML request). Long and short forms are also available for other EML statements.
- The
SET FIELDS WITHaddition is available as another field specification option. However, it has limitations that you should be aware of. It can cause syntax warnings. Check the documentation. It is recommended that you useFIELDS ... WITHandFROM.
Update Operations
*&---------------------------------------------------------------------*
*& Short form of EML MODIFY statement
*&---------------------------------------------------------------------*
"The example code snippet uses data objects declared upfront instead of
"inline declarations.
DATA: upd_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m,
failed_resp TYPE RESPONSE FOR FAILED zdemo_abap_rap_ro_m,
reported_resp TYPE RESPONSE FOR REPORTED zdemo_abap_rap_ro_m.
"Note:
"The BDEF derived type does not have a %cid component but %cid_ref
"to refer to an existing instance (its %cid value) within the same
"EML request. The example includes the reference to an existing
"instance using %cid_ref for demonstration purposes, commented out.
"The example does not include an actually referable instance. When
"there is no referable instance, a runtime error occurs.
upd_tab = VALUE #(
( key_field = 1 field1 = 'A' field2 = 'B' field3 = 1 field4 = 2 )
( key_field = 2 field1 = 'C' field2 = 'D' field3 = 3 field4 = 4 )
"( %cid_ref = `some_cid` field1 = 'E' field2 = 'F' field3 = 5 field4 = 6 )
).
"Note:
"- The statement includes the field specification option FIELDS ( ... ) WITH.
" The fields to be respected are included in the parentheses. For these,
" %control is flagged as if_abap_behv=>mk-on. The others, field3 and field4,
" are not specified. Therefore, %control is flagged as if_abap_behv=>mk-off
" for these fields.
"- Typically, the key fields are not included since changing them is ruled
" out in the example's BDEF: field ( readonly:update ) key_field;
"- The EML statement does not have the mapped response parameter. No
" new instance are created in update operations.
MODIFY ENTITY zdemo_abap_rap_ro_m
UPDATE
FIELDS ( field1 field2 ) WITH upd_tab
FAILED failed_resp
REPORTED reported_resp.
*&---------------------------------------------------------------------*
*& Long form of EML MODIFY statement
*&---------------------------------------------------------------------*
"Note:
"- The statement's operands are all declared inline.
"- The statement includes the field specification option FROM.
"- This specification option requires %control to be filled explicitly.
" Unlike the previous example, the update operation also respects
" field3 and field4, indicated by flagging all non-key components with
" if_abap_behv=>mk-on. As above, changing the key values is ruled out.
" Flagging key_field with if_abap_behv=>mk-on results in a runtime error.
"- See the excursion with specifying the %control component values.
" Applying the coding technique mentioned there (providing the corresponding
" values for all table lines outside of the inner parentheses), you can
" save the specification of code lines.
"- As above, an example with %cid_ref is included but commented out since
" the example does not inlcude a referable instance.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
UPDATE
FROM VALUE #(
( key_field = 4 field1 = 'G' field2 = 'H' field3 = 7 field4 = 8
%control = VALUE #( key_field = if_abap_behv=>mk-off
field1 = if_abap_behv=>mk-off
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) )
( key_field = 5 field1 = 'I' field2 = 'J' field3 = 9 field4 = 10
%control = VALUE #( key_field = if_abap_behv=>mk-off
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) )
* ( %cid_ref = `another_cid` field1 = 'K' field2 = 'L' field3 = 11 field4 = 12
* %control = VALUE #( key_field = if_abap_behv=>mk-off
* field1 = if_abap_behv=>mk-on
* field2 = if_abap_behv=>mk-on
* field3 = if_abap_behv=>mk-on
* field4 = if_abap_behv=>mk-on ) )
)
FAILED DATA(f_resp)
REPORTED DATA(r_resp).
Delete Operations
*&---------------------------------------------------------------------*
*& Short form of EML MODIFY statement
*&---------------------------------------------------------------------*
"The example code snippet uses data objects declared upfront instead of
"inline declarations.
DATA: del_tab TYPE TABLE FOR DELETE zdemo_abap_rap_ro_m,
failed_response TYPE RESPONSE FOR FAILED zdemo_abap_rap_ro_m,
reported_response TYPE RESPONSE FOR REPORTED zdemo_abap_rap_ro_m.
"Note:
"The BDEF derived type only includes components to identify instances.
"This can be either referring to an existing existing using %cid_ref
"- its %cid value - within the same EML request, or the key. The example
"includes the reference to an existing instance using %cid_ref for
"demonstration purposes, commented out. The example does not include an
"actually referable instance. When there is no referable instance, a
"runtime error occurs.
del_tab = VALUE #(
( key_field = 1 )
( key_field = 2 )
"( %cid_ref = `some_cid` )
).
"Note:
"EML MODIFY staments for delete operations can only use the field
"specification option FROM.
MODIFY ENTITY zdemo_abap_rap_ro_m
DELETE
FROM del_tab
FAILED failed_response
REPORTED reported_response.
*&---------------------------------------------------------------------*
*& Long form of EML MODIFY statement
*&---------------------------------------------------------------------*
"Note:
"The statement's operands are all declared inline.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
DELETE
FROM VALUE #(
( key_field = 4 )
( key_field = 5 )
"( %cid_ref = `another_cid` )
)
FAILED DATA(f_del_resp)
REPORTED DATA(r_del_resp).
Dynamic Form of ABAP EML MODIFY Statements
- The code snippet demonstrates the dynamic form
MODIFY ENTITIES OPERATIONS .... - Using the statement, you can execute multiple modify operations for multiple RAP BOs in a single statement.
- Find more information here.
DATA: op_tab TYPE abp_behv_changes_tab,
create_root_tab TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m,
update_root_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m,
delete_root_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ro_m,
cba TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m\_child,
update_child_tab TYPE TABLE FOR UPDATE zdemo_abap_rap_ch_m,
delete_child_tab TYPE TABLE FOR DELETE zdemo_abap_rap_ch_m.
create_root_tab = VALUE #(
( %cid = 'cid1'
key_field = 5
%control-key_field = if_abap_behv=>mk-on
field1 = 'a'
%control-field1 = if_abap_behv=>mk-on
field2 = 'b'
%control-field2 = if_abap_behv=>mk-on )
( %cid = 'cid2'
key_field = 6
%control-key_field = if_abap_behv=>mk-on
field1 = 'd'
%control-field1 = if_abap_behv=>mk-on
field2 = 'd'
%control-field2 = if_abap_behv=>mk-on )
( %cid = 'cid3'
key_field = 7
%control-key_field = if_abap_behv=>mk-on
field1 = 'e'
%control-field1 = if_abap_behv=>mk-on
field2 = 'f'
%control-field2 = if_abap_behv=>mk-on ) ).
update_root_tab = VALUE #(
( %cid_ref = 'cid2'
field1 = 'g'
%control-field1 = if_abap_behv=>mk-on
field2 = 'h'
%control-field2 = if_abap_behv=>mk-on ) ).
cba = VALUE #(
( %cid_ref = 'cid1'
%target = VALUE #( (
%cid = 'cid_cba1'
key_ch = 10
%control-key_ch = if_abap_behv=>mk-on
field_ch1 = 'i'
%control-field_ch1 = if_abap_behv=>mk-on
field_ch2 = 1
%control-field_ch2 = if_abap_behv=>mk-on
) ) )
( %cid_ref = 'cid2'
%target = VALUE #( (
%cid = 'cid_cba2'
key_ch = 20
%control-key_ch = if_abap_behv=>mk-on
field_ch1 = 'j'
%control-field_ch1 = if_abap_behv=>mk-on
field_ch2 = 2
%control-field_ch2 = if_abap_behv=>mk-on
) ) )
( %cid_ref = 'cid3'
%target = VALUE #( (
%cid = 'cid_cba3'
key_ch = 30
%control-key_ch = if_abap_behv=>mk-on
field_ch1 = 'k'
%control-field_ch1 = if_abap_behv=>mk-on
field_ch2 = 3
%control-field_ch2 = if_abap_behv=>mk-on
) ) ) ).
update_child_tab = VALUE #(
( key_field = 6
field_ch1 = 'l'
%control-field_ch1 = if_abap_behv=>mk-on
field_ch2 = 4
%control-field_ch2 = if_abap_behv=>mk-on ) ).
delete_root_tab = VALUE #( ( key_field = 7 ) ).
delete_child_tab = VALUE #( ( key_field = 7 ) ).
op_tab = VALUE #(
( op = if_abap_behv=>op-m-create
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
instances = REF #( create_root_tab ) )
( op = if_abap_behv=>op-m-update
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
instances = REF #( update_root_tab ) )
( op = if_abap_behv=>op-m-delete
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
instances = REF #( delete_root_tab ) )
( op = if_abap_behv=>op-m-create_ba
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
sub_name = '_CHILD'
instances = REF #( cba ) )
( op = if_abap_behv=>op-m-update
entity_name = 'ZDEMO_ABAP_RAP_CH_M'
instances = REF #( update_child_tab ) )
( op = if_abap_behv=>op-m-delete
entity_name = 'ZDEMO_ABAP_RAP_CH_M'
instances = REF #( delete_child_tab ) )
).
MODIFY ENTITIES OPERATIONS op_tab
MAPPED DATA(m)
FAILED DATA(f)
REPORTED DATA(r).
Executing Actions
- A RAP action is a non-standard operation that modifies the state of a RAP BO entity instance.
- Various flavors of actions are available. Find more information here.
- To execute actions, use the syntax
MODIFY ... EXECUTE ....
"Example snippet taken from the executable example
"The long form of the MODIFY statement is used. It includes
"a create operation and executes an action.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field field1 field2 field3 field4 )
WITH VALUE #(
( %cid = 'cid_x2'
key_field = 7
field1 = 'ooo'
field2 = 'ppp'
field3 = 70
field4 = 71 ) )
EXECUTE multiply_by_2 FROM VALUE #(
"Executing action via %cid_ref
( %cid_ref = 'cid_x2' )
"Executing action via key
( key_field = 1 )
( key_field = 2 ) )
MAPPED DATA(mapped)
FAILED DATA(failed)
REPORTED DATA(reported).
Excursions
Specifying %control Component Values in the Short Form of VALUE Constructor Expressions
- The following EML statement creates RAP BO instances. The BDEF derived type is created inline.
- With the
FROMaddition, the%controlvalues must be specified explicitly. - There is also a short form of
VALUEconstructor expressions. In this case, you can provide the corresponding values for all table lines outside of the inner parentheses, instead of individually specifying the values for each instance within the parentheses. - The corresponding
%controlcomponent value is then assigned for all of the following table lines.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FROM VALUE #(
%control-key_field = if_abap_behv=>mk-on
%control-field1 = if_abap_behv=>mk-on
%control-field2 = if_abap_behv=>mk-on
%control-field3 = if_abap_behv=>mk-on
%control-field4 = if_abap_behv=>mk-off
( %cid = 'cid1'
key_field = 1
field1 = 'aaa'
field2 = 'bbb'
field3 = 10
field4 = 100 )
( %cid = 'cid2'
key_field = 2
field1 = 'ccc'
field2 = 'ddd'
field3 = 20
field4 = 200 ) )
MAPPED DATA(m)
FAILED DATA(f)
REPORTED DATA(r).
Combining Multiple Operations in One ABAP EML Request
The following EML statement combines multiple operations in one EML request. It demonstrates the use of the BDEF derived type components %cid and %cid_ref.
- First, two instances are created by specifying
%cid. - An update operation in the same request only specifies a certain field within the parentheses of the
FIELDS ( ... ) WITHaddition which denotes that only this particular field should be updated. - The other field values remain unchanged.
- The reference to the instance is made via
%cid_ref. - Consider an EML request in which no instance to refer to using
%cid_refexists, e. g. for an update operation. You can also make the reference using the unique key. - A delete operation is available in the same request, too.
DELETEcan only be followed by the additionFROM.- In contrast to other derived types, the derived type that is expected here (
TYPE TABLE FOR DELETE) only has%cid_refand the key as components.
MODIFY ENTITIES OF root_ent
ENTITY root
CREATE FIELDS ( key_field field1 field2 ) WITH
VALUE #( ( %cid = 'cid4' key_field = 4
field1 = 'G' field2 = 'H' )
( %cid = 'cid5' key_field = 5
field1 = 'I' field2 = 'J' ) )
UPDATE FIELDS ( field2 ) WITH
VALUE #( ( %cid_ref = 'cid4' field2 = 'Z' ) )
DELETE FROM
VALUE #( ( %cid_ref = 'cid5' ) "Instance referenced via %cid_ref
( key_field = 9 ) ) "Instance referenced via the key
...
Creating Instances for the Root and Child Entity (Deep Create)
The following code snippet shows a deep create.
- First, an instance is created for the root entity.
- Then, in the same request, instances are created for the child entity based on the root instance.
- In the example below, the assumption is that a composition is specified in the root view entity like
composition [1..*] of root_ent as _childandkey_fieldandkey_field_childare the keys of the child view entity. - The structured component
%targetenters the picture here which contains the target's primary key and data fields.
MODIFY ENTITIES OF root_ent
ENTITY root_ent
CREATE FIELDS ( key_field field1 field2 ) WITH
VALUE #( ( %cid = 'cid6' key_field = 6
field1 = 'I' field2 = 'J' ) )
CREATE BY \_child
FIELDS ( key_field_child field1_child field2_child ) WITH
VALUE #( ( %cid_ref = 'cid6'
%target = VALUE #( ( %cid = 'cid_child_1'
key_field_child = 1
field1_child = 'aa'
field2_child = 'bb' )
( %cid = 'cid_child_2'
key_field_child = 2
field1_child = 'cc'
field2_child = 'dd' ) ) ) )
...
ABAP EML Syntax for Reading Operations
- Read-only operations always return a result, i.e. the syntax of the
EML statement requires the addition
RESULTand an operand. - When RAP BO instances are read, the returned data include the current status of instances in the transactional buffer which includes unsaved modifications on instances. If an instance is not yet available in the transactional buffer, the currently persisted data set is (automatically - in case of a managed scenario) read into the transactional buffer.
- Note that read operations are always implicitly enabled for each entity listed in a BDEF, i. e. there is no extra definition in the BDEF in contrast to, for example, create or update.
Reading Operations
- The following code snippet shows the long form of the EML
READstatement for reading instances from the root entity. - In
READstatements, the additionsFIELDS ( ... ) WITHandFROMcan also be used to specify the fields that you intend to read. Here, the additionALL FIELDS WITHis available for reading all field values. - There are also short and dynamic forms of the statement.
READ ENTITIES OF root_ent
ENTITY root_ent
ALL FIELDS WITH
VALUE #( ( key_field = 1 ) "Derived type TYPE TABLE FOR READ IMPORT only includes the keys
( key_field = 2 ) )
RESULT DATA(result)
FAILED DATA(f)
REPORTED DATA(r).
Read-by-Association Operations
- Read-by-association operations include the optional addition
LINKwith which you can retrieve the keys of the source and target (i. e. the associated entity). - The by-association operations work reciprocally, i. e. you can, for example, read a child instance via the parent and a parent instance via the child, too.
"Read-by association operation: parent to child
READ ENTITIES OF root_ent
ENTITY root_ent
BY \_child
ALL FIELDS WITH VALUE #( ( key_field = 1 ) )
RESULT DATA(rba_res1)
LINK DATA(links1).
...
"Read-by association operation: child to parent
READ ENTITIES OF root_ent
ENTITY child_ent
BY \_parent
ALL FIELDS WITH VALUE #( ( key_field = 1 key_field_child = 1 ) )
RESULT DATA(rba_res2)
LINK DATA(links2).
...
Dynamic ABAP EML READ Statements
In addition to the short and long forms described above, various ABAP EML statements also have dynamic forms.
Taking EML read operations as an example, the following code snippet shows a dynamic EML READ ENTITIES statement. The relevant syntax element is the OPERATIONS addition.
The dynamic form allows the collection of read operations for multiple RAP BOs in one EML statement.
For more information, see the ABAP keyword documentation and the comments in the snippet.
"The statement is taken from the executable example. The example has a
"root entity and a child entity. For both entities, RAP BO instances
"are to be read (read and read-by-association operation).
DATA:
"The following data object is the operand of the dynamic EML statement
"It is an internal table and has a special, RAP-specific type.
op_tab TYPE abp_behv_retrievals_tab,
"More data object declarations (internal tables typed with BDEF
"derived types) that are relevant for the EML statement.
"For both entities (root and child), RAP BO instances are to be
"read. The internal tables are used for components of the internal
"table op_tab further down.
read_dyn TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m,
read_dyn_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m,
rba_dyn TYPE TABLE FOR READ IMPORT zdemo_abap_rap_ro_m\_child,
rba_dyn_result TYPE TABLE FOR READ RESULT zdemo_abap_rap_ro_m\_child,
rba_dyn_link TYPE TABLE FOR READ LINK zdemo_abap_rap_ro_m\_child.
"Filling the internal tables, i.e. which instances are to be read
"Root entity
"Example:
"- The key is comprised of the field 'key_field'. It is of type i.
"- The %control structure is filled, flagging those fields that
" are to be read. Flagging the key field is not required.
read_dyn = VALUE #(
( %key-key_field = 1
%control = VALUE #(
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) )
( %key-key_field = 2
%control = VALUE #(
field1 = if_abap_behv=>mk-on
field2 = if_abap_behv=>mk-on
field3 = if_abap_behv=>mk-on
field4 = if_abap_behv=>mk-on ) ) ).
"Child entity
"Instances to be read for a read-by-association operation
"The shared key is 'key_field'.
rba_dyn = VALUE #(
( %key-key_field = 1
%control = VALUE #(
key_ch = if_abap_behv=>mk-on
field_ch1 = if_abap_behv=>mk-on
field_ch2 = if_abap_behv=>mk-on ) )
( %key-key_field = 2
%control = VALUE #(
key_ch = if_abap_behv=>mk-on
field_ch1 = if_abap_behv=>mk-on
field_ch2 = if_abap_behv=>mk-on ) ) ).
"Filling the internal table that is the operand of the
"dynamic EML statement
"This table has optional and mandatory components.
op_tab = VALUE #(
( "op: Specifies the operation to be executed; is mandatory;
" can be set with the predefined constants, e.g. OP-R-READ
" etc., of interface IF_ABAP_BEHV
op = if_abap_behv=>op-r-read
"entity_name: Specifies the name of the RAP BO entity for which
" the operation is executed; is mandatory
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
"instances: Specifies a reference to an internal table holding
" the input keys; must be appropriately typed; is mandatory
instances = REF #( read_dyn )
"results: Specifies a reference to an internal table with the required
" BDEF derived type for the read results; is mandatory
results = REF #( read_dyn_result ) )
( op = if_abap_behv=>op-r-read_ba
entity_name = 'ZDEMO_ABAP_RAP_RO_M'
"sub_name: Only relevant for specifying association names in
" read-by-association operations; in that context, it is mandatory
sub_name = '_CHILD'
"full: Optional flag; specifies if all target instances are to be retrieved
full = abap_true
instances = REF #( rba_dyn )
results = REF #( rba_dyn_result )
"links: Reference to internal table holding the key pairs of the source and
" target
links = REF #( rba_dyn_link ) ) ).
READ ENTITIES OPERATIONS op_tab.
Accessing Change Information
- ABAP EML read operations using
WITH CHANGESprovide access to accumulated change information for RAP BO instances within a RAP transaction. - Syntax:
- Short form:
READ ENTITY IN LOCAL MODE ... WITH CHANGES ... - Long form:
READ ENTITIES OF ... IN LOCAL MODE ENTITY ... WITH CHANGES ... - Regarding the dynamic form, see the notes further down.
- Short form:
- After
RESULT, the BDEF derived typeTYPE TABLE FOR READ CHANGESis expected. - In addition to RAP BO instance data, the read result includes the component
%chg, which indicates the accumulated operation. - Restrictions:
- Available only with managed RAP BOs (not applicable to unmanaged RAP BOs)
- Usable only in implementation classes
- Must be used in conjunction with
IN LOCAL MODE - Cannot be applied to read-by-association operations or when executing RAP functions.
- The addition helps determine whether a RAP BO instance is unchanged or has been created, updated, or deleted during the current RAP transaction. The
%controlstructure components in the read result indicate which fields have changed, but only for those components where the%chgvalue is eitherif_abap_behv=>cop-create,if_abap_behv=>cop-update, orif_abap_behv=>cop-recreate. In all other cases, the%controlcomponent value remains initial. - With regard to the dynamic form,
WITH CHANGEScannot be specified. The functionality ofWITH CHANGESis implemented in dynamic ABAP EMLREADstatements by setting thefullcomponent of the statement's operand toif_abap_behv=>typekind-result_chg.
Example statements
"Short form
DATA read_changes TYPE TABLE FOR READ CHANGES demo_rap_entity.
READ ENTITY IN LOCAL MODE demo_rap_entity
WITH CHANGES
ALL FIELDS WITH CORRESPONDING #( keys )
RESULT read_changes
FAILED failed.
"Dynamic form
DATA: op_tab TYPE abp_behv_retrievals_tab,
read_dyn TYPE TABLE FOR READ IMPORT demo_rap_entity,
read_dyn_result TYPE TABLE FOR READ CHANGES demo_rap_entity,
entity TYPE abp_entity_name VALUE 'DEMO_RAP_ENTITY'.
read_dyn = VALUE #( FOR wa IN keys (
%key-key_field = wa-key_field
%control-field1 = if_abap_behv=>mk-on
%control-field2 = if_abap_behv=>mk-on
%control-field3 = if_abap_behv=>mk-on
%control-field4 = if_abap_behv=>mk-on ) ).
op_tab = VALUE #( (
op = if_abap_behv=>op-r-read
entity_name = entity
full = if_abap_behv=>typekind-result_chg
instances = REF #( read_dyn )
results = REF #( read_dyn_result ) ) ).
READ ENTITIES IN LOCAL MODE OPERATIONS op_tab FAILED DATA(f).
COMMIT ENTITIES: Persisting to the Database
- A
COMMIT ENTITIESstatement triggers the RAP save sequence. Without such a statement, the modified RAP BO instances that are available in the transactional buffer are not persisted to the database. In case of a natively supported RAP scenario (for example, when using OData), theCOMMIT ENTITIESrequest is executed automatically. COMMIT ENTITIESimplicitly includesCOMMIT WORK.- Note:
COMMIT ENTITIESstatements cannot be used in behavior implementations. - There are multiple variants available for the statement as described in the ABAP Keyword Documentation here. They deal with different variants of how to handle RAP responses, among others.
COMMIT ENTITIESstatements set the system fieldsy-subrc. When usingCOMMIT ENTITIES, it is not guaranteed thatCOMMIT WORKis carried out successfully. Hence, you should include a check forsy-subrcafterCOMMIT ENTITIESso that you can react to failures accordingly.
| Variant/Addition | Notes |
|
Short form of |
The following snippet shows a create operation. This operation has only
an impact on the database with the
|
|
Long form of |
The long syntax form includes the retrieval of information for one or more RAP BO entities. Root entities must be specified.
|
|
Dynamic form of |
The dynamic syntax form allows you to retrieve RAP responses from RAP saver methods by dynamically specifying one or more RAP BO root entities.
|
|
Specifying a commit scope |
|
|
Simulating a commit |
|
ROLLBACK ENTITIES
- The
ROLLBACK ENTITIESstatement rolls back all changes of the current RAP transaction. - This rollback includes the clearing of the transactional buffer (by calling the
cleanupmethod) and locks. - Note that in unmanaged scenarios, you must implement the behavior yourself. For example, the
cleanupmethod must include an appropriate implementation to clear the transactional buffer. - Same as for
COMMIT ENTITIES, in natively supported RAP scenarios, such as an SAP Fiori application using OData, theROLLBACK ENTITIEScall is implicitly and automatically performed by the RAP runtime engine.
The following example demonstrates the effect of ROLLBACK ENTITIES. In the second loop pass, ROLLBACK ENTITIES clears the transactional buffer, leaving nothing to commit. Therefore, the assertions are also true for the second loop.
DELETE FROM zdemo_abap_rapt1.
DO 2 TIMES.
MODIFY ENTITIES OF zdemo_abap_rap_ro_m
ENTITY root
CREATE FIELDS ( key_field )
AUTO FILL CID WITH VALUE #( ( key_field = sy-index ) )
MAPPED DATA(m1)
FAILED DATA(f1)
REPORTED DATA(r1).
IF sy-index = 2.
ROLLBACK ENTITIES.
ENDIF.
COMMIT ENTITIES.
IF sy-subrc <> 0.
...
ENDIF.
SELECT FROM zdemo_abap_rapt1
FIELDS key_field
ORDER BY key_field
INTO TABLE @DATA(tab).
ASSERT lines( tab ) = 1.
ASSERT tab[ 1 ]-key_field = 1.
ENDDO.
GET PERMISSIONS: Retrieving Information about RAP BO Permissions
- RAP BO permissions cover aspects such as global and instance authorization, or global, instance, and static feature control.
- Using ABAP EML
GET PERMISSIONSstatements, you can retrieve information about these permissions. - Like other ABAP EML statements,
GET PERMISSIONSoffers multiple (optional) additions and syntax variants. - Find more information here and in the subtopics.
- The example code snippet uses the short form of
GET PERMISSIONS, specifying an only clause. TheONLY GLOBALaddition ensures the result includes only global authorization, global and static feature control. - Unlike many other ABAP EML statements, the
GET PERMISSIONSexample statement works with a data object having a structured BDEF derived type (afterREQUEST), not a tabular BDEF derived type.
DATA request TYPE STRUCTURE FOR PERMISSIONS REQUEST zdemo_abap_rap_ro_m.
request = VALUE #(
%create = if_abap_behv=>mk-on
%update = if_abap_behv=>mk-on
%delete = if_abap_behv=>mk-on
%field-key_field = if_abap_behv=>mk-on
%field-field1 = if_abap_behv=>mk-on
%field-field2 = if_abap_behv=>mk-on
%field-field3 = if_abap_behv=>mk-on
%field-field4 = if_abap_behv=>mk-on ).
GET PERMISSIONS ONLY GLOBAL ENTITY zdemo_abap_rap_ro_m
REQUEST request
RESULT DATA(result)
FAILED DATA(failed)
REPORTED DATA(reported).
SET LOCKS: Exclusively Locking Instances
- To modify RAP BO instances, they must be locked first. The RAP framework automatically locks these instances for subsequent modifications by the user.
- If the RAP BO consumer needs an exclusive lock to prevent other users from modifying the same instance simultaneously, you can use the ABAP EML
SET LOCKSstatements to establish enqueue locks for RAP BO instances. This will prevent concurrent modifications. - The lock remains active until the RAP transaction concludes.
- Three statement forms are available:
- Short form (
SET LOCKS ENTITY ...): Locks instances of a single RAP BO entity. - Long form (
SET LOCKS OF ...): Locks instances of multiple RAP BO entities in a CDS composition tree. - Dynamic form (
SET LOCKS locks_tab ...): Collects instances of multiple RAP BO entities.
- Short form (
- The short and long forms require the BDEF derived type
TYPE TABLE FOR KEY OF, which is an internal table containing instance key values. The dynamic form uses an internal table of typeABP_BEHV_LOCKS_TAB.
Example code snippet illustrating all forms:
DATA key_tab TYPE TABLE FOR KEY OF zdemo_abap_rap_ro_u.
key_tab = VALUE #( ( key_field = 1 )
( key_field = 2 ) ).
"Short form
SET LOCKS ENTITY zdemo_abap_rap_ro_u
FROM key_tab
FAILED DATA(f_short).
"Long form
"The statements specifies the key table inline.
SET LOCKS OF zdemo_abap_rap_ro_u
ENTITY root FROM VALUE #( ( key_field = 1 ) )
ENTITY child FROM VALUE #( ( key_field = 2 ) )
FAILED DATA(f_long)
REPORTED DATA(r_long).
"Dynamic form
DATA root_keys TYPE TABLE FOR KEY OF zdemo_abap_rap_ro_u.
DATA child_keys TYPE TABLE FOR KEY OF zdemo_abap_rap_ch_u.
root_keys = VALUE #( ( key_field = 1 ) ).
child_keys = VALUE #( ( key_field = 2 )
( key_field = 3 ) ).
"Populating the lock table that is of type abp_behv_locks_tab
"Components:
"- entity_name: Name of RAP BO entity in capital letters
"- instances: Reference to an internal table typed with the derived type TYPE TABLE FOR KEY OF
DATA(locks_tab) = VALUE abp_behv_locks_tab(
( entity_name = 'ZDEMO_ABAP_RAP_RO_U' instances = REF #( root_keys ) )
( entity_name = 'ZDEMO_ABAP_RAP_CH_U' instances = REF #( child_keys ) ) ).
SET LOCKS locks_tab FAILED DATA(f_dyn)
REPORTED DATA(r_dyn).
The code in the collapsible section illustrates the effect of a SET LOCKS statement using artifacts from the ABAP cheat sheet repository.
🟢 Click to expand for example code
- This simplified example visualizes the locking of RAP BO instances using a
SET LOCKSstatement. - To explore the example, create two demo classes that implement the
if_oo_adt_classruninterface. As a prerequisite, the ABAP cheat sheet repository has been imported into the system. - Class 1:
- Prepares a demo database table and inserts four entries.
- Uses a
SET LOCKSstatement (in its short form) to lock two instances (key fields with value 1 and 2). - An
ASSERTstatement is included to set a breakpoint.
CLASS zcl_class1 DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_class1 IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
DELETE FROM zdemo_abap_rapt1.
MODIFY zdemo_abap_rapt1 FROM TABLE @( VALUE #( ( key_field = 1 )
( key_field = 2 )
( key_field = 3 )
( key_field = 4 ) ) ).
DATA key_tab TYPE TABLE FOR KEY OF zdemo_abap_rap_ro_u.
key_tab = VALUE #(
( key_field = 1 )
( key_field = 2 ) ).
SET LOCKS ENTITY zdemo_abap_rap_ro_u
FROM key_tab
FAILED DATA(f)
REPORTED DATA(r).
ASSERT 1 = 1.
ENDMETHOD.
ENDCLASS.
- Class 2:
- Includes:
- Using the
cl_abap_lock_object_factoryclass to enqueue instances. - Specifying another
SET LOCKSstatement.
- Using the
- Both attempt to lock instances with key values 1 to 4.
cl_abap_lock_object_factoryclass calls include adding information to theenqstring table, and the failed response parameterfis specified for theSET LOCKSstatement.
- Includes:
CLASS zcl_class2 DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_class2 IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
DATA key_tab TYPE TABLE FOR KEY OF zdemo_abap_rap_ro_u.
key_tab = VALUE #( ( key_field = 1 )
( key_field = 2 )
( key_field = 3 )
( key_field = 4 ) ).
DATA enq TYPE string_table.
TRY.
DATA(lo_lock) = cl_abap_lock_object_factory=>get_instance( iv_name = 'EZDEMO_ABAP_LOCK' ).
LOOP AT key_tab REFERENCE INTO DATA(lr_key).
APPEND |key_field = { lr_key->key_field }| TO enq.
TRY.
lo_lock->enqueue( it_parameter = VALUE #(
( name = 'KEY_FIELD' value = REF #( lr_key->key_field ) ) ) ).
APPEND | - Enqueue ok| TO enq.
CATCH cx_abap_foreign_lock INTO DATA(err_foreign_lock).
APPEND | - { err_foreign_lock->get_text( ) }| TO enq.
CATCH cx_abap_lock_failure INTO DATA(err_lock_failure).
APPEND | - { err_lock_failure->get_text( ) }| TO enq.
ENDTRY.
ENDLOOP.
CATCH cx_abap_lock_failure INTO err_lock_failure.
APPEND err_lock_failure->get_text( ) TO enq.
ENDTRY.
out->write( enq ).
SET LOCKS ENTITY zdemo_abap_rap_ro_u
FROM key_tab
FAILED DATA(f).
out->write( f ).
ENDMETHOD.
ENDCLASS.
-
How to proceed:
- In class 1, set a breakpoint on the
ASSERTstatement. - Run class 1 and enter the debugger. Leave the debugger session open. This indicates that the RAP transaction is not yet complete.
- Run class 2.
- The expected outcome is as follows: The
SET LOCKSstatement in class 1 locks two instances (1 and 2) out of four. Consequently, thecl_abap_lock_object_factorycalls and the additionalSET LOCKSstatement in class 2 should generate errors for attempting to lock instances with key values 1 and 2, since they are already locked.
- In class 1, set a breakpoint on the
-
The
enqstring table should contain the following entries, and the failed response parameterfshould have two entries for 1 and 2 with the failure cause locked.key_field = 1 - Object is locked by user ... key_field = 2 - Object is locked by user ... key_field = 3 - Enqueue ok key_field = 4 - Enqueue ok
Raising RAP Business Events
- RAP business events can be raised in ABAP behavior pools with
RAISE ENTITY EVENTstatements, typically in the save phase. - The focus of the snippets is on the local consumption of RAP business events. Prerequisites:
eventspecifications are available in the BDEF (e.g.... event some_evt; ...). For more details, refer to the BDL documentation.- A RAP event handler class is available that is used to implement RAP event handler methods.
- Note that these methods are called asynchronously.
- Similar to RAP handler and saver methods, RAP event handler methods are implemented in the CCIMP include (Local Types tab in ADT) of the RAP event handler class.
- To locally consume RAP business events, a local class that inherits from
CL_ABAP_BEHAVIOR_EVENT_HANDLERcan be implemented in the CCIMP include of a RAP event handler class.
- More information:
- ABAP for RAP Business Events in the ABAP Keyword Documentation
- Business Events in the SAP Help Portal
*&---------------------------------------------------------------------*
*& Syntax for the declaration part of a global RAP event handler class
*&---------------------------------------------------------------------*
CLASS cl_event_handler DEFINITION PUBLIC FOR EVENTS OF some_bdef.
...
ENDCLASS.
*&---------------------------------------------------------------------*
*& Syntax for the declaration part of a local event handler class
*& in the CCIMP include of a RAP event handler class
*&---------------------------------------------------------------------*
CLASS lhe_event DEFINITION INHERITING FROM cl_abap_behavior_event_handler.
...
ENDCLASS.
*&---------------------------------------------------------------------*
*& RAP event handler method definition
*&---------------------------------------------------------------------*
"Notes:
"- Must be defined as instance methods in the private visibility section.
"- The input parameter par is an internal table of type TYPE TABLE FOR EVENT.
"- This type includes the keys of RAP BO instances (and %param, if the event
" is specified with a parameter in the BDEF)
"- The methods do not contain RAP response parameters.
METHODS meth FOR ENTITY EVENT par FOR some_bdef~some_evt.
*&---------------------------------------------------------------------*
*& RAISE ENTITY EVENT statement in an ABP, e.g. the save_modified method
*& in managed scenarios with additional save
*&---------------------------------------------------------------------*
...
CLASS lsc IMPLEMENTATION.
METHOD save_modified.
"Assumption: An event is specified for create operations in the BDEF as follows
"event created;
IF create-some_bdef IS NOT INITIAL.
RAISE ENTITY EVENT some_bdef~created
FROM VALUE #( FOR <cr> IN create-root ( %key = VALUE #( some_key = <cr>-some_key ) ) ).
ENDIF.
"Assumption: An event is specified for delete operations in the BDEF as follows
"event deleted parameter some_abstract_entity;
"The abstract entity has two parameters, for example, with which additional
"information can be passed.
IF delete-some_bdef IS NOT INITIAL.
RAISE ENTITY EVENT some_bdef~deleted
FROM VALUE #( FOR <del> IN delete-some_bdef (
%key = VALUE #( some_key = <del>-some_key )
%param = VALUE #( par_a = '01'
par_b = 'Item deleted' ) ) ).
ENDIF.
ENDMETHOD.
ENDCLASS.
Additions to ABAP EML Statements in ABAP Behavior Pools
There are a special additions when using EML in behavior pools.
IN LOCAL MODE Addition
- Using the
IN LOCAL MODEaddition to ABAP EMLREADandMODIFYstatements can be used to suppress feature controls, authorization checks, and prechecks. - Consider the following use case: There is a field to display the
booking status of a trip on a UI. In the BDEF, this field is
specified as read-only. Hence, it cannot be modified by a user on
the UI. However, there is a button on the UI to book the trip. This
button might trigger an action to book the trip so that the value of
the field changes from open to booked. To enable this, the
underlying handler method for the modify operation with the action
to be executed has the addition
IN LOCAL MODEthat ignores the feature control.
Syntax:
MODIFY ENTITIES OF root_ent IN LOCAL MODE
ENTITY root
EXECUTE book
FROM action_tab
...
AUGMENTING Addition to ABAP EML MODIFY Statements
- ABAP EML
MODIFYstatements include a special syntax variant used only in the context of projections:MODIFY AUGMENTING ENTITY|ENTITIES.- RAP projection business objects prepare a business object for specific services, allowing flexible service consumption and role-based service design. Find more details in the Development guide for the ABAP RESTful Application Programming Model.
- Purpose: Modify and enrich requests from the base BO at the projection layer before storing the data in the transactional buffer. All standard operations and actions are supported.
- You can use the statement with the
AUGMENTINGaddition only in RAP BO providers. - Response parameters are not supported with these statements.
- Note the
RELATINGaddition in this context. This is relevant if the augmented request contains instances not in the original request. It establishes a relationship between the new instances and the original ones in a relationship table to associate potential responses.
MODIFY AUGMENTING ENTITY some_bdef
UPDATE FROM ...
"relates_tab is of type abp_behv_relating_tab
MODIFY AUGMENTING ENTITY some_bdef
UPDATE FROM ... RELATING TO some_instances BY relates_tab.
RAP Excursions
Using Keys and Identifying RAP BO Instances in a Nutshell
The following bullet points outline important aspects regarding keys and identifying RAP BO instances in ABAP EML statements.
Why is it important?
- The primary key of a RAP BO entity instance is composed of one or more key fields.
- These key fields stand for the fields that are specified with
keyin the underlying CDS view entity of the RAP BO. - The primary key uniquely identifies each RAP BO entity instance.
- As a general rule, after the creation of an instance including the primary key during a RAP create operation, the primary key can no longer be changed.
- Note that there are different numbering concepts, such as early and late numbering. In the latter concept, newly created entity instances are given their final key only shortly before saving in the database. Until then, the business logic uses a temporary key that has to be replaced.
- If a data set with a particular primary key already exists in the persistent database table, the saving of a RAP BO instance is rejected because of a duplicate primary key.
How can a RAP BO instance be uniquely identified?
- It can be done by using a RAP instance identifier or RAP content identifier or both of them.
- RAP instance identifier:
- It consists of the primary key fields and all relevant BDEF derived type components.
- To ease the reference to all of these components, special component groups are available to summarize the components and make them addressable via one single name.
%key: Contains the primary key fields of a RAP BO instance%tky: Specifies the transactional key. Comprises%key(and, thus, the primary key fields of a RAP BO instance) and more components that are relevant to uniquely identify a RAP BO instance. Among them,%pid(relevant for late numbering scenarios) and the draft indicator%is_draft(relevant for draft scenarios). In non-late numbering or non-draft scenarios, these extra components are just blank. However, it is recommended that you use%tkyin all scenarios since it simplifies a possible later switch, for example, to a draft scenario. In doing so, lots of adaptations to the code regarding the keys and the inclusion of%is_draftcan be avoided.
- RAP content identifier:
- Reflected in the component
%cidwhich is a string of typeABP_BEHV_CIDto define a content ID. - Used as a unique and preliminary identifier for RAP BO instances in RAP create operations, especially where no primary key exists for the particular instance.
- For newly created instances, the ID can then be used for performing further modifications, referencing to those instances using
%cid_ref(which has the same value as %cid), for example, in RAP operations usingCREATE BY,UPDATEandDELETE, as well as actions withEXECUTE). - In contrast to the primary key and the preliminary ID
%pidfor late numbering scenarios,%cid(and%cid_ref) are only available on a short-term basis for the current ABAP EML request within the RAP interaction phase in one RAP transaction. - Note: Specify
%cideven if there are no further operations referring to it.
- Reflected in the component
- Special case: Late numbering
- In late numbering scenarios newly created entity instances are given their final key only shortly before saving in the database, i. e. you deal with preliminary keys in the RAP interaction phase and the early phase of the RAP save sequence.
- In this case, you can use
%keyto hold the preliminary keys or use a preliminary ID in the dedicated component%pidwhich is of typeABP_BEHV_PIDand only available in late numbering scenarios. - Similar to above, to uniquely identify RAP BO instances in late
numbering scenarios, you can use either
%keyor%pidor both of them. In any case, the use of%tkyis handy because it includes both components. You must ensure that%tkyin total uniquely identifies the instances. - Note: A further component group to refer to the keys is available:
%pky.%pkycontains%pidand%keyin late numbering scenarios. In non-late numbering scenarios, it just contains%key.%pkyitself is contained in%tky. There are contexts, for example, particular actions, where%tkyis not available but%pkyis. This way, there is still the option to summarize%pidand%keyin one component group in the absence of%tky.
General rule: A RAP BO instance must - where available - always be uniquely
identifiable by its transactional key (%tky) for internal
processing during the RAP interaction phase. %tky always
contains all relevant components for the chosen scenario.
Assignment of Key Component Groups
- As a general best practice, you should use a RAP BO instance key component group when referring to the entire key, rather than listing the individual key fields. It is recommended that you use
%tkywhenever possible. - Avoid specifying multiple keys. For example, check the F2 information to understand what is included in the component groups to avoid redundancy. You should avoid specifying a component group and a key separately if the group already includes that key.
- In the following cases, type compatibility cannot be guaranteed in component group assignments:
- Mixing key component groups when they refer to the same RAP BO entity, e.g.
wa-%tky = wa-%key. Such an assignment should also be avoided when both component groups have an identical scope in terms of components (e.g.%tkyand%keyin non-late-numbering and non-draft scenarios). - Mixing the same key component groups when referring to two different RAP BO entities, for example,
wa_root-%tky = wa_child-%tky. In this case, adding more components later may cause syntax errors for an assignment that worked previously. - Defining structured types that have the same components as key component groups, and then assigning data objects of that type to those of the respective, original key component group.
- Mixing key component groups when they refer to the same RAP BO entity, e.g.
- In the above cases, the
CORRESPONDINGoperator can be used to ensure type compatibility in assignments to key component groups:... %tky = CORRESPONDING #( wa-%tky ) ... ... %key = CORRESPONDING #( wa-%key ) ... ... %pky = CORRESPONDING #( wa-%pky ) ... - In cases where different data objects of key component groups of a BDEF derived type are to be assigned to the same key component group of the same entity, a direct assignment works without a syntax warning because the content is identical. A direct assignment is recommended (
...wa1_root-%tky = wa2_root-%tky ...). The use of theCORRESPONDINGoperator is unnecessary and less performant. This is true, for example, for key component group assignments in the context of RAP response parameters failed and reported.
RAP Concepts
RAP numbering
- A concept that deals with setting values for primary key fields.
- There are multiple options to handle the numbering for primary key fields depending on when (early in the RAP interaction phase or late in the RAP save sequence) and by whom (RAP BO consumer, behavior pool, or framework) the primary key values are set.
- When:
- Early numbering: The final key values are assigned during a RAP create operation in the interaction phase.
- Late numbering:
The final key values are assigned during the RAP save sequence
(and here only in the RAP saver method
adjust_numbers).
- By whom
- External numbering: Key values are provided by the RAP BO consumer. For example, in a create operation, the key values are specified by the RAP BO consumer like other non-key field values. Basically, this is the concept with which the snippets above are tailored.
- Internal numbering: Key values are provided by the RAP BO provider. For example, in a create operation, the key values are not specified in an EML create request by the RAP BO consumer but rather by the RAP BO provider. In case of a managed RAP BO, the key is automatically created by the framework which only works if the key is of a certain type (16-character byte-like UUID). In case of an unmanaged RAP BO, the key values are provided in a dedicated handler method which must be self-implemented. Note that late numbering is internal by default since no further RAP BO consumer interaction is possible in the late phase of the RAP save sequence.
Draft
- The draft concept in RAP allows the content of the transactional buffer to be stored in intermediate storages (draft tables) in order to allow transactions to expand over different ABAP sessions.
- Like the concepts mentioned above, a RAP BO can be draft-enabled in the BDEF. If enabled, the application allows data modifications and the temporary storage of modifications but does not yet persist them to the database. The users of the application can continue modifying this data later and they might even use a different device from the one where they modified the data previously.
- The draft indicator
%is_draftis available for RAP BO instance identification. It is used to indicate if a RAP BO instance is a draft instance or an active instance. Conveniently, the component group%tkycontains%is_draft.%is_draftcan then be addressed via%tky.
Late Numbering and Key Identification in the Late Phase of the RAP Save Sequence
- Context: RAP saver method
adjust_numbersin which the final key values are assigned; the preliminary keys can be included in%keyor%pidor both of them. %pidand the preliminary key values in%keyare automatically assigned to the following components when reaching theadjust_numbersmethod:%tmp: A component that is assigned the preliminary key values contained in%key. In doing so,%tmptakes over the role that%keyhas had in the RAP interaction phase to hold the preliminary key values.%pidremains as is. The component group%precontains%pidand%tmpand, thus, all preliminary identifiers.
- In the
adjust_numbersmethod, the preliminary keys are transformed into the final keys, i. e. the preliminary keys are mapped to%key(which holds the final keys in this context) in themappedresponse parameter. - Depending on your use case to use either
%pidor (the preliminary key values in)%key(which is%tmphere in this method) during the interaction phase or both of them, you must ensure that%prein total (since it contains both%pidand%tmp) is unique and mapped to the final keys that are to be contained in%key.
Ensuring Data Consistency in a RAP Transaction
The LUW concept, which deals with the transfer of data from one consistent state to another, applies to applications using RAP. RAP transactions are integrated with the SAP LUW, which is a prerequisite for transactional consistency. RAP provides a standardized approach and rules (RAP BO contract) for the RAP business object (BO) runtime to ensure that the RAP transaction is correctly implemented, data inconsistencies are avoided, and the SAP LUW is successfully completed.
Phases of a RAP Transaction
A RAP transaction is divided into two phases during the runtime of a RAP BO, while the second phase can be divided into two subphases that serve different purposes.

- RAP handler methods are called in a RAP handler class that inherits from
CL_ABAP_BEHAVIOR_HANDLER. - New data, i.e. RAP BO instances, are created in the RAP transactional buffer, or persisted data is retrieved and inserted into the transactional buffer for further processing.
- The state of the data may become inconsistent in the transactional buffer during this phase. However, the data remains consistent in the database because changes are made only in the transactional buffer.
- The RAP save sequence is triggered by a
COMMIT ENTITIESstatement. In natively supported RAP scenarios, such as an SAP Fiori application using OData, theCOMMIT ENTITIEScall is implicitly and automatically performed by the RAP runtime engine. - RAP saver methods are called in the RAP saver class, which inherits from the base class
CL_ABAP_BEHAVIOR_SAVER, in a specific order. - Is divided into the RAP early save phase (ensures that the RAP BO instances in the transactional buffer - all RAP BOs in the current RAP transaction are involved - are in a consistent state so that they can be saved to the database) and the RAP late save phase (to finally save data from the transactional buffer to the database).
(Optional:) Saver methods called in the RAP early save phase:
-
finalize: For final calculations and data changes before saving. In managed scenarios, determinations specified withON SAVEare called when reaching this method. -
check_before_save: For data consistency checks in the transactional buffer. In managed scenarios, validations specified withON SAVEare called when this method is reached. -
cleanup_finalize: If there are failures in at least one of the previous saver methods, further processing with the RAP late save phase is rejected and the transaction returns to the interaction phase. Before that, this saver method is called, allowing changes made in the finalize method to be rolled back.
If there are errors in the early save phase, sy-subrc returns the value 4 after COMMIT ENTITIES statements. If the data in the transactional buffer is consistent after the early save phase, the late save phase is processed, which also means that a point of no return has been reached. Unlike the early save phase, you cannot return to the interaction phase when you reach the late save phase. Either the RAP transaction ends with a successful commit, or the changes are rolled back and a runtime error occurs.
Saver methods called in the RAP late save phase:
adjust_numbers: Provides RAP BO instances with their final numbers. This method is available only in late numbering scenarios.save(orsave_modifiedin managed scenarios with an unmanaged or additional save): Used to save data from the transactional buffer to the database. If there are no issues, the final database commit is triggered and an implicitCOMMIT WORKis executed.
cleanup method: After a successful save, the cleanup method clears the transactional buffer. It completes the save sequence.
Commit and Rollback in a RAP Transaction
The default ABAP statements for RAP are COMMIT ENTITIES (triggers the RAP save sequence and the final database commit; in natively supported RAP scenarios, the commit is performed implicitly and automatically by the RAP runtime engine) and ROLLBACK ENTITIES (rolls back all changes of the current RAP transaction, i.e. the transactional buffer is cleared by calling the cleanup method). Both are RAP-specific and end the RAP transaction.
Notes on COMMIT ... and ROLLBACK ... statements due to the integration of RAP transactions into the SAP LUW:
COMMIT ENTITIESimplicitly triggersCOMMIT WORK.- Using
COMMIT WORKin RAP (instead ofCOMMIT ENTITIES) also triggers the RAP save sequence. If there are no errors in the RAP save sequence, the final database commit is successful. Only in this best-case scenario doesCOMMIT WORKhave the same effect asCOMMIT ENTITIES. However, if there are errors in the save sequence, a runtime error occurs in any case, while a return to the interaction phase is still possible when usingCOMMIT ENTITIES. COMMIT ENTITIESprovides RAP-specific functionality with various additions that are not possible withCOMMIT WORK, such as RAP responses can be retrieved, key conversion in late numbering scenarios, checking a RAP transaction in a simulation mode.- There are short, long, and dynamic forms of
COMMIT ENTITIESstatements. COMMIT ENTITIESstatements implicitly enforce local updates withCOMMIT WORK, orCOMMIT WORK AND WAITif the local update fails. Therefore, the update is either a local update or a synchronous update, but never an asynchronous update. WhenCOMMIT WORKis used, the RAP BO consumer can choose between synchronous and asynchronous update for RAP BO entities.ROLLBACK ENTITIESimplicitly triggersROLLBACK WORK. Both have the same effect when used in RAP. Therefore, they are interchangeable.
[!NOTE] Special Case: Failures in the Late Save Phase
- In exceptional cases, for example, when BAPIs are called to save RAP BO instances in the late save phase, it may happen that the basic rule that failures must not occur in the RAP late save phase and be detected in the RAP early save phase is violated.
- In such cases, the base class
CL_ABAP_BEHAVIOR_SAVER_FAILEDcan be used for the RAP saver class.- RAP BO consumers can be informed by filling the RAP response parameters (some of which are not available when using
CL_ABAP_BEHAVIOR_SAVERas the base class) in the saver method implementation so that they can react accordingly.- After a
COMMIT ENTITIESstatement and a failure in the late save phase,sy-subrcis set to 8.- A subsequent RAP operation may result in a runtime error. If the RAP BO consumer is to continue after an error in the late phase of the RAP save sequence, an explicit
ROLLBACK ENTITIESis required.
Allowed/Forbidden Operations in a Behavior Implementation in a RAP Transaction
The following restrictions apply to operations and/or statements in the individual phases of a RAP transaction in ABAP behavior implementations. Note that, depending on setting the strict mode in the BDEF, runtime errors may occur due to the use of forbidden statements, or static code checks may be applied. Note that most operations/statements refer to the use in the unrestricted ABAP language scope.
| Operations/Statements | Interaction phase | Early save phase | Late save phase | Notes |
|---|---|---|---|---|
| Database commits using secondary connections (unrestricted ABAP language scope) |
X | X | X | Secondary connections are allowed for infrastructure purposes, for example. They can be used to store data that is not part of the main transaction, such as application logs, traces, or number ranges. |
| Database commits using the standard connection (unrestricted ABAP language scope) |
X | X | - | Database commits can be made in phases other than the late phase, for example, by calling external services or using a WAIT statement. |
sRFC (CALL FUNCTION ... DESTINATION), aRFC (CALL FUNCTION ... STARTING NEW TASK) (unrestricted ABAP language scope) |
X | X | - | Allowed in phases other than the late save phase, e.g. for the purpose of parallelization within the application. It is up to the application to ensure consistency, e.g. to ensure read-only access, to handle a potential two-phase commit, or to provide a proper error handling. |
| Database modifications | - | - | X | Only allowed in the late save phase because the data being processed is always potentially inconsistent. Database changes in other phases would result in multiple database transactions instead of one transaction, which would disrupt the SAP LUW. |
Update function module (CALL FUNCTION ... IN UPDATE TASK) (unrestricted ABAP language scope) |
- | - | X | Can be used to ensure that there is only one database transaction. In addition, registering function modules for update tasks at stages other than the late save phase would interfere with RAP draft scenarios, for example, where data is stored in draft tables. There is no way to unregister function modules once they have been registered. |
bgRFC (CALL FUNCTION ... IN BACKGROUND UNIT) (unrestricted ABAP language scope) |
- | - | X | |
tRFC, qRFC (CALL FUNCTION ... IN BACKGROUND TASK) (unrestricted ABAP language scope) |
- | - | - | Obsolete technologies. |
PERFORM ON COMMIT, PERFORM ON ROLLBACK (unrestricted ABAP language scope) |
(X) | (X) | X | Basically possible in all phases, but should be reserved for the late save. Note: The use of these statements indicates improper integration with RAP. It is especially important to check draft scenarios when calling legacy code and using these statements. Instead, ABAP EML or procedure calls that do not include a COMMIT WORK should be used. |
Transaction control COMMIT WORK, ROLLBACK WORK |
X/- | X/- | X/- | When a transactional phase has been explicitly set by methods of the CL_ABAP_TX class (find more information here), the transaction owner is allowed to execute a commit or rollback statement. In the contexts of RAP (that is, where RAP is the transaction owner, for example, in handler and saver methods), local consumption of RAP business events, bgPF, and classified APIs, commit or rollback statements are not allowed. |
Dynpro processing (e.g. SET SCREEN, CALL SCREEN, LEAVE SCREEN, CALL DIALOG, SUPPRESS DIALOG, MESSAGE without INTO, WRITE, STOP) (unrestricted ABAP language scope) |
- | - | - | Not allowed in ABAP behavior implementations. Results in a runtime error. |
Transaction processing (CALL TRANSACTION, LEAVE TRANSACTION) (unrestricted ABAP language scope) |
- | - | - | Not allowed to prevent (unwanted) integration of other LUWs. |
Raising an exception (RAISE EXCEPTION) |
- | - | - | It is not allowed to leave a RAP transaction this way. |
Raising a RAP business event using RAISE ENTITY EVENT |
- | - | X | The statements are recommended in the save and save_modified RAP saver methods. |
Report processing (SUBMIT ...) (unrestricted ABAP language scope) |
- | - | - | Not allowed in transactional contexts. Results in a syntax or runtime error. SUBMIT ... AND RETURN does not currently return an error, but it leads to potentially unwanted screen processing, and because of the missing return channel, there is no proper error handling. |
RAP Additional and Unmanaged Save
-
As covered in the RAP terms section, managed is an implementation type that is specified in the BDEF, and which determines the RAP BO provider, and thus, how the transactional buffer is provided and how the behavior of a RAP BO is implemented.
-
In a managed RAP BO, the RAP framework automatically executes the save, eliminating the need for any additional logic. However, you can modify this behavior by adding or replacing the default save logic. This is not applicable to unmanaged BOs, where the save is user-defined.
-
RAP additional save
- This feature enhances the default save sequence by incorporating additional save logic.
- You can apply this additional save logic to the entire BO or a specific entity.
- For example, you can add functionality to be executed during the save, such as change documents or writing to an application log.
- The relevant BDEF syntax is
with additional savemanaged with additional save implementation in class bp_some_abp unique; strict(2); ... - The additional save logic is implemented in the
save_modifiedRAP saver method. save_modifiedhas three importing parameters with specific BDEF derived types:createof typeREQUEST FOR CHANGE ...updateof typeREQUEST FOR CHANGE ...deleteof typeREQUEST FOR DELETE ...- These BDEF derived types are deep structures containing internal tables with RAP BO instance keys and/or data, i.e. they contain those instances that are to be created, updated or deleted.
- Optional additions are available in the BDEF. With the specification in the code snippet above, by default, only the values of the key fields and changed fields are passed to the
save_modifiedmethod. Using the additionwith full data, you can, as the name implies, pass all instance data:managed with additional save with full data implementation in class ....
-
RAP unmanaged save
- This feature replaces the default managed save logic with a custom save logic.
- BDEF syntax:
managed with unmanaged save implementation in class bp_some_abp unique; strict(2); ... - Also in this case, ...
- you can apply the save logic to the entire BO or an individual entity.
- the implementation is done in the
save_modifiedRAP saver method.
-
More information:
- ABAP Keyword Documentation
- Development guide for the ABAP RESTful Application Programming Model:
Handling Dependencies on RAP Business Objects in ABAP Unit
The ABAP Unit Tests cheat sheet includes an example demonstrating the handling of dependencies on RAP business objects:
- Creating transactional buffer test doubles using the
CL_BOTD_TXBUFDBL_BO_TEST_ENVclass - Mocking ABAP EML APIs using the
CL_BOTD_MOCKEMLAPI_BO_TEST_ENVclass
Note that there is a RAP-specific variant of the CREATE OBJECT statement available. CREATE OBJECT ... FOR TESTING. enables the instantiation of RAP handler classes. Find more information in the Development guide for the ABAP RESTful Application Programming Model.
RAP-Related System Classes and Functionality
Several RAP-related system classes and functionality are available, including (some of them are mentioned in the cheat sheet):
-
Classes related to implementations of the saver class:
CL_ABAP_BEHAVIOR_SAVER: Saver classes inherit from that classCL_ABAP_BEHAVIOR_HANDLER: Saver classes can inherit from that class in special cases, e.g. when failures in the late save phase cannot be ruled out
-
Class related to RAP business events
CL_ABAP_BEHAVIOR_EVENT_HANDLER: An event handler class inherits from that class
-
Classes related to ABAP Unit
CL_BOTD_TXBUFDBL_BO_TEST_ENV: For creating transactional buffer test doublesCL_BOTD_MOCKEMLAPI_BO_TEST_ENV: For mocking ABAP EML APIs
-
CL_ABAP_TXclass providing methods for setting transactional phases- This class is not exclusively related to RAP since the setting of transactional phases is implicitly done in RAP. However, it is, for example, relevant in the context of the local consumption of RAP business events when, for example, database modifications are performed in the event handler implementations.
- Find more information here.
-
CL_ABAP_BEHV_AUXclass providing methods for retrieving various types of information, including:-
Details about the current RAP transactional phase, such as the RAP early save phase, RAP late save phase, or RAP interaction phase (using the
GET_CURRENT_PHASEmethod) -
Context information for the current RAP handler and saver method (accessed through the
GET_CURRENT_CONTEXTmethod) -
The method kind (obtained via the
GET_CURRENT_HANDLER_KINDmethod)"Context information for the current handler cl_abap_behv_aux=>get_current_context( IMPORTING in_local_mode = FINAL(loc_mode) call_kind = FINAL(call) draft_activate = FINAL(dr_act) draft_user = FINAL(dr_user) for_permissions = FINAL(for_perm) from_behavior = FINAL(fr_behv) from_interface = FINAL(fr_int) from_projection = FINAL(fr_proj) privileged = FINAL(priv) ).
-
-
get_bdef_derived_typemethod in the context of RTTI for creating BDEF derived types dynamically, and theget_base_typemethod for retrieving the BDEF derived type (or dictionary type)"TYPE TABLE FOR DATA dref_itab TYPE REF TO data. "Getting a type description object for a BDEF derived type DATA tab_der_type_create TYPE TABLE FOR CREATE zdemo_abap_rap_ro_m. DATA(tdo_tab_bdef_derived_type) = cl_abap_tabledescr=>get_bdef_derived_type( p_entity = 'ZDEMO_ABAP_RAP_RO_M' p_kind = abp_bdef_derived_type-create ). CREATE DATA dref_itab TYPE HANDLE tdo_tab_bdef_derived_type. "Getting type information and checking type compatibility DATA(tdo_for_dref_tab_der_type) = CAST cl_abap_tabledescr( cl_abap_typedescr=>describe_by_data( dref_itab->* ) ). DATA(applies_to_tab_der_type) = tdo_for_dref_tab_der_type->applies_to_data( tab_der_type_create ). ASSERT applies_to_tab_der_type = abap_true. "TYPE STRUCTURE FOR DATA dref_struc TYPE REF TO data. "Getting a type description object for a BDEF derived type DATA struc_der_type_create TYPE STRUCTURE FOR CREATE zdemo_abap_rap_ro_m. DATA(tdo_struc_bdef_derived_type) = cl_abap_structdescr=>get_bdef_derived_type( p_entity = 'ZDEMO_ABAP_RAP_RO_M' p_kind = abp_bdef_derived_type-create ). CREATE DATA dref_struc TYPE HANDLE tdo_struc_bdef_derived_type. "Getting type information and checking type compatibility DATA(tdo_for_dref_struc_der_type) = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_data( dref_struc->* ) ). DATA(applies_to_struc_der_type) = tdo_for_dref_struc_der_type->applies_to_data( struc_der_type_create ). ASSERT applies_to_struc_der_type = abap_true. "Retrieving the BDEF derived type or dictionary type using the get_base_type method TYPES der_type1 TYPE STRUCTURE FOR READ RESULT zdemo_abap_rap_ro_m. TYPES der_type2 TYPE der_type1. FINAL(tdo1) = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'DER_TYPE1' ) ). FINAL(tdo2) = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'DER_TYPE2' ) ). FINAL(abs_name1) = tdo1->absolute_name. FINAL(abs_name2) = tdo2->absolute_name. FINAL(base_type1) = tdo1->get_base_type( ). FINAL(base_type2) = tdo2->get_base_type( ). FINAL(abs_name_base1) = base_type1->absolute_name. FINAL(abs_name_base2) = base_type2->absolute_name. TYPES carr_tab_type TYPE zdemo_abap_carr. FINAL(tdo3) = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'CARR_TAB_TYPE' ) ). FINAL(abs_name3) = tdo3->absolute_name. FINAL(base_type3) = tdo3->get_base_type( ). FINAL(abs_name_base3) = base_type3->absolute_name.
More Information
- Section ABAP for RAP Business Objects in the ABAP Keyword Documentation including EML
- RAP Glossary
- Development guide for the ABAP RESTful Application Programming Model
- RAP Contract: Rules for the RAP BO provider and consumer implementation to ensure consistency and reliability
- The Authorization Checks cheat sheet includes high-level information and provides links on authorization control in RAP.
Executable Examples
main Branch
This cheat sheet is supported by different executable examples demonstrating various scenarios:
- Demo RAP scenario with a managed RAP BO, external numbering: zcl_demo_abap_rap_ext_num_m
- Demo RAP scenario with an unmanaged RAP BO, external numbering: zcl_demo_abap_rap_ext_num_u
- Demo RAP scenario ("RAP calculator") with a managed, draft-enabled RAP BO, late numbering zcl_demo_abap_rap_draft_ln_m
- Demonstrating the local consumption of RAP business events in the context of a RAP demo scenario (managed RAP BO with managed internal numbering and additional save): zcl_demo_abap_rap_m_as
[!NOTE]
- To reduce the complexity, the executable examples only focus on the technical side. ABAP classes play the role of a RAP BO consumer here.
- The examples do not represent real life scenarios and are not suitable as role models for proper RAP scenarios. They rather focus on the technical side by giving an idea how the communication and data exchange between a RAP BO consumer and RAP BO provider can work. Additionally, the examples show how the methods for non-standard RAP BO operations might be self-implemented in an ABAP behavior pool.
- Due to the simplification, the examples do not entirely meet all requirements of the RAP BO contract and do not represent semantic or best practice examples.
- You can check out the "RAP calculator" example using the preview version of an SAP Fiori Elements UI. See the comments in the class for more information.
- The steps to import and run the code are outlined here.
- Disclaimer
rap Branch
The ABAP cheat sheets GitHub repository features simplified, non-semantic demo RAP BOs in the rap branch for exploring various RAP-related features, syntax, and concepts in simple contexts. Topics include managed and unmanaged RAP BOs, draft-enabled RAP BOs, numbering concepts like early and late numbering, field-specific characteristics, standard operations (CRUD), actions as non-standard operations, authorizations, local RAP business events, and more.
Unlike the examples included in the main branch - they primarily focus on ABAP EML and include ABAP classes as RAP BO consumers - the example RAP BOs in the rap branch are set up to be explored using preview SAP Fiori UIs.
For more detailed information and semantic RAP examples, refer to the Development guide for the ABAP RESTful Application Programming Model and the ABAP Flight Reference Scenario for the ABAP RESTful Application Programming Model.