我想从现有CDS视图中的一个类中调用一个方法来获取某些数据,这些数据只能由这个方法调用。所以我想从 CDS 视图中调用一个方法。
最简单的方法是什么?
我会很高兴有一个代码示例。
注意:您的abap 逻辑只会在CDS 视图被处理注释的东西(即公开为Odata 服务)使用时执行,但不会在事务SE16N 或Eclipse 中的预览中执行。其实有两种方式。第一个选项:
@AbapCatalog.sqlViewName: 'ZV_TEST_ABAP'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'ABAP code in cds'
@OData.publish: true
define view YCDS_WITH_ABAP as select from sflight
{
//sflight
key carrid,
key connid,
key fldate,
seatsocc_f,
@ObjectModel.readOnly: true
@ObjectModel.virtualElement: true
@ObjectModel.virtualElementCalculatedBy: 'ABAP:YCL_CDS_FUNCTION' //ycl_cds_function
cast( '' as abap.char(255)) as text
}where connid = '0017'
你的abap课程:
CLASS ycl_cds_function DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES: if_sadl_exit_calc_element_read.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS ycl_cds_function IMPLEMENTATION.
METHOD if_sadl_exit_calc_element_read~calculate.
DATA:
lt_calculated_data TYPE STANDARD TABLE OF ZV_TEST_ABAP .
" it_original_data -> data that comes from cds
" lt_calculated_data -> data that you will manipulate
MOVE-CORRESPONDING it_original_data TO lt_calculated_data.
" do your extra logic and append/update your cds view data
LOOP AT lt_calculated_data ASSIGNING FIELD-SYMBOL(<fs_data>).
<fs_data>-text = 'hello from abap!'.
ENDLOOP.
MOVE-CORRESPONDING lt_calculated_data TO ct_calculated_data.
ENDMETHOD.
METHOD if_sadl_exit_calc_element_read~get_calculation_info.
ENDMETHOD.
ENDCLASS.
...,{
"__metadata": {
"id": "lalala')",
"uri": "blablabla')",
"type": "YCDS_WITH_ABAP_CDS.YCDS_WITH_ABAPType"
},
"carrid": "AA",
"connid": "0017",
"fldate": "/Date(1535068800000)/",
"seatsocc_f": 20,
"text": "hello from abap!"
},...
第二种选择:
第二种方法是使用自定义类更改服务的 DPC 类,该类继承此标准类并在这些重新定义的方法中执行您的自定义逻辑。就个人而言,我会选择第二种选择。我没有尝试过,但我感觉性能会更好。:)
有关更多信息,请查看:https ://blogs.sap.com/2020/05/11/abap-code-exits-in-cds-views/
虽然从 OData 的角度来看,@Oguz 的答案值得了解,但还有一个纯 CDS 解决方案适用于从 CDS 视图中选择的每个组件,与它们是否支持注释无关。
首先,您将 CDS 视图指定为SELECT FROM <table function>
:
@AbapCatalog.sqlViewName: 'MYCDSVIEW'
define view MY_CDS_VIEW as select from MY_TABLE_FUNCTION {
A,
B
}
然后定义一个表函数。表函数类似于 CDS 视图,只是它们的执行逻辑是在 ABAP 中实现的,而不是在 SQL 脚本中:
define table function MY_TABLE_FUNCTION
returns
{
A : some_type;
B : some_type;
}
implemented by method
cl_my_table_function=>provide_data_for_tf_test;
最后,提供实现表函数的 ABAP 类:
CLASS cl_my_table_function DEFINITION
PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_amdp_marker_hdb.
CLASS-METHODS provide_data FOR TABLE FUNCTION MY_TABLE_FUNCTION.
ENDCLASS.
CLASS cl_my_table_function IMPLEMENTATION.
METHOD provide_data
BY DATABASE FUNCTION FOR HDB LANGUAGE SQLSCRIPT
USING some_table.
RETURN
SELECT A, B
FROM some_table;
ENDMETHOD.
ENDCLASS.
当你做这样的事情时,花一些额外的时间来测试客户端处理。这种方式的组合通常会降低 ABAPers 从 SELECT 语句和常规 CDS 视图中知道的自动客户端添加。您可能需要@ClientHandling: { type: #CLIENT_DEPENDENT }
在涉及的 CDS 视图上进行注释,并让表函数显式提供 CLIENT 或 MANDT 列。