Generación de Código RAP: Usar ADT Generator y Fiori Tools

Kategorie
RAP
Veröffentlicht
Autor
Johannes

La creación manual de todos los artefactos RAP consume tiempo: tablas, CDS Views, Behavior Definitions, Service Bindings - todo suma rápidamente una docena de objetos. Con los generadores RAP en ADT y el Fiori Elements App Generator puede acelerar drásticamente este proceso.

¿Por qué generación de código?

Un stack RAP completo con Draft Handling típicamente incluye:

1. Tabla de base de datos
2. Tabla Draft
3. Interface CDS View
4. Projection CDS View
5. Metadata Extension
6. Behavior Definition
7. Behavior Implementation
8. Service Definition
9. Service Binding

Crear estos nueve objetos manualmente y vincularlos correctamente toma tiempo - especialmente con convenciones de nomenclatura consistentes y sintaxis correcta. El RAP Generator crea todo esto en pocos clics.

RAP Generator en ADT

El RAP Generator está integrado directamente en ABAP Development Tools (ADT) y genera Business Objects RAP completos a partir de definiciones de tablas.

Requisitos Previos

  • SAP S/4HANA 2022 o más reciente
  • SAP BTP ABAP Environment
  • ABAP Development Tools (Eclipse)

Paso 1: Iniciar el Generador

Clic derecho en tabla de base de datos
→ Generate ABAP Repository Objects
→ Generate RAP BO

Alternativamente:

Clic derecho en paquete
→ New → Other ABAP Repository Object
→ Business Services → Generate RAP BO

Paso 2: Seleccionar Tabla

Seleccione la tabla principal para su Business Object. Para nuestro ejemplo de reserva de vuelo:

Tabla: ZFLIGHT_BOOK

El generador reconoce automáticamente:

  • Campos clave
  • Campos administrativos (created_by, last_changed_at, etc.)
  • Asociaciones a otras tablas

Paso 3: Opciones de Generación

OpciónDescripciónRecomendación
Implementation TypeManaged o UnmanagedManaged para casos estándar
Draft HandlingCon o sin DraftCon Draft para apps de edición
Data ModelSingle o JerarquíaJerarquía con Parent-Child
ProjectionCon capa ProjectionSí para aplicaciones UI

Para el escenario de reserva de vuelo:

Implementation Type: Managed
Draft Handling: Yes
Data Model: Single BO
Projection: Yes

Paso 4: Configurar Nombres

El generador sugiere nombres basados en la tabla:

Tabla: ZFLIGHT_BOOK
Interface View: ZI_FLIGHTBOOK
Projection View: ZC_FLIGHTBOOK
Behavior Def: ZI_FLIGHTBOOK
Service Definition: ZUI_FLIGHTBOOK
Service Binding: ZUI_FLIGHTBOOK_O4

Ajuste según sus convenciones de nomenclatura - prefijos consistentes son importantes:

I_ = Interface Layer
C_ = Consumption/Projection Layer
UI_ = UI Service
_O4 = OData V4

Paso 5: Ejecutar Generación

Después de hacer clic en “Finish”, se crean todos los objetos:

┌─────────────────────────────────────────────────────────┐
│ Objetos Generados │
├─────────────────────────────────────────────────────────┤
│ ✓ ZDRAFT_FLIGHT_BOOK (Tabla Draft) │
│ ✓ ZI_FLIGHTBOOK (Interface CDS View) │
│ ✓ ZI_FLIGHTBOOK (Behavior Definition) │
│ ✓ ZBP_I_FLIGHTBOOK (Behavior Implementation) │
│ ✓ ZC_FLIGHTBOOK (Projection CDS View) │
│ ✓ ZC_FLIGHTBOOK (Projection Behavior) │
│ ✓ ZUI_FLIGHTBOOK (Service Definition) │
│ ✓ ZUI_FLIGHTBOOK_O4 (Service Binding) │
└─────────────────────────────────────────────────────────┘

Entender los Artefactos Generados

Interface CDS View

El generador crea una Interface View completa:

@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Booking'
define root view entity ZI_FlightBook
as select from zflight_book
{
key booking_uuid,
flight_id,
customer_id,
booking_date,
seat_number,
status,
price,
currency_code,
@Semantics.user.createdBy: true
created_by,
@Semantics.systemDateTime.createdAt: true
created_at,
@Semantics.user.lastChangedBy: true
last_changed_by,
@Semantics.systemDateTime.lastChangedAt: true
last_changed_at,
@Semantics.systemDateTime.localInstanceLastChangedAt: true
local_last_changed
}

Importante: Las anotaciones @Semantics se establecen automáticamente para nombres de campo conocidos.

Behavior Definition

managed implementation in class zbp_i_flightbook unique;
strict ( 2 );
with draft;
define behavior for ZI_FlightBook alias FlightBook
persistent table zflight_book
draft table zdraft_flight_book
etag master LocalLastChanged
lock master total etag LastChangedAt
authorization master ( global )
{
field ( readonly )
BookingUUID,
CreatedBy,
CreatedAt,
LastChangedBy,
LastChangedAt,
LocalLastChanged;
field ( numbering : managed )
BookingUUID;
create;
update;
delete;
draft action Activate optimized;
draft action Discard;
draft action Edit;
draft action Resume;
draft determine action Prepare;
}

Behavior Implementation

La clase generada contiene estructuras básicas para Local Handler:

CLASS lhc_FlightBook DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS:
get_global_authorizations FOR GLOBAL AUTHORIZATION
IMPORTING REQUEST requested_authorizations FOR FlightBook
RESULT result.
ENDCLASS.
CLASS lhc_FlightBook IMPLEMENTATION.
METHOD get_global_authorizations.
" Implementar aquí verificaciones de autorización propias
ENDMETHOD.
ENDCLASS.

Personalizar Objetos Generados

Después de la generación, típicamente necesita extender los objetos:

1. Agregar Anotaciones UI

En la Projection View o Metadata Extension:

@UI.headerInfo: {
typeName: 'Reserva de Vuelo',
typeNamePlural: 'Reservas de Vuelo',
title: { value: 'FlightID' }
}
@UI.lineItem: [{ position: 10 }]
@UI.identification: [{ position: 10 }]
FlightID;
@UI.lineItem: [{ position: 20 }]
@UI.selectionField: [{ position: 10 }]
BookingDate;

2. Agregar Validaciones

En la Behavior Definition:

define behavior for ZI_FlightBook alias FlightBook
...
{
validation validateBookingDate on save { field BookingDate; }
validation validateSeat on save { field SeatNumber; }
}

En la Implementation:

METHOD validateBookingDate.
READ ENTITIES OF zi_flightbook IN LOCAL MODE
ENTITY FlightBook
FIELDS ( BookingDate )
WITH CORRESPONDING #( keys )
RESULT DATA(bookings).
LOOP AT bookings INTO DATA(booking).
IF booking-BookingDate < cl_abap_context_info=>get_system_date( ).
APPEND VALUE #( %tky = booking-%tky ) TO failed-flightbook.
APPEND VALUE #( %tky = booking-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = 'La fecha de reserva debe estar en el futuro' )
%element-BookingDate = if_abap_behv=>mk-on
) TO reported-flightbook.
ENDIF.
ENDLOOP.
ENDMETHOD.

3. Agregar Custom Actions

define behavior for ZI_FlightBook alias FlightBook
...
{
action confirmBooking result [1] $self;
action cancelBooking result [1] $self;
}

Fiori Elements App Generator

Después del backend RAP, puede generar el frontend con el Fiori Elements App Generator.

En Business Application Studio

1. Abrir Command Palette (F1)
2. Escribir "Fiori: Open Application Generator"
3. Elegir Template: "List Report Page" o "Worklist"
4. Fuente de datos: Seleccionar OData V4 Service
5. Introducir Service Binding: ZUI_FLIGHTBOOK_O4
6. Elegir entidad principal: FlightBook
7. Asignar nombre al proyecto

Estructura de App Generada

flight-booking-app/
├── webapp/
│ ├── manifest.json # Configuración de App
│ ├── Component.js # UI5 Component
│ ├── index.html # Página inicial
│ └── localService/ # Datos mock
├── package.json # Dependencias
└── ui5.yaml # Configuración de build

Personalizar manifest.json

Los ajustes más importantes:

{
"sap.app": {
"title": "{{appTitle}}",
"description": "{{appDescription}}"
},
"sap.ui5": {
"routing": {
"targets": {
"FlightBookList": {
"options": {
"settings": {
"initialLoad": true,
"variantManagement": "Page"
}
}
}
}
}
}
}

Generador vs. Manual: Ayuda para la Decisión

EscenarioGeneradorManual
Proyecto Greenfield nuevoRecomendadoNo
App CRUD estándarRecomendadoNo
Jerarquías complejasParcialmenteRequiere ajuste parcial
Migración de LegacyNoSí, para control
Escenario UnmanagedLimitadoMayormente manual
Aprendizaje/TrainingNoSí, para comprensión
PrototipadoRecomendadoNo

¿Cuándo usar el Generador?

Recomendado:

  • Nuevas aplicaciones estándar
  • Escenario Managed con Draft
  • Prototipos rápidos
  • Importante convenciones de nomenclatura consistentes

Preferir manual:

  • Unmanaged con integración Legacy
  • Jerarquías BO complejas
  • Requisitos especiales de estructura
  • Proyectos de aprendizaje para entender RAP

Ajustes Típicos Después de la Generación

Lista de verificación para objetos generados

Ajustar después de la generación:
□ Interface View
□ @EndUserText.label para todos los campos
□ Asociaciones a otras Entities
□ @ObjectModel.text para campos de texto
□ Projection View
□ Definir @UI.headerInfo
□ @UI.lineItem para List Report
□ @UI.identification para Object Page
□ @UI.selectionField para filtros
□ Behavior Definition
□ Agregar validaciones
□ Determinations para valores por defecto
□ Definir Custom Actions
□ Configurar verificaciones de autorización
□ Service Binding
□ Activar Publish
□ Probar Preview en navegador

Mejores Prácticas

1. Generar, luego Personalizar

Use el generador como punto de partida - no como producto terminado:

Generador → Estructura básica → Personalización → Testing → Refinamiento

2. Definir Convenciones de Nomenclatura Previamente

Antes de generar, defina prefijos:

Z = Namespace de cliente
I_ = Interface Layer
C_ = Consumption Layer
A_ = Abstract Entity
UI_ = UI Service
_O4 = OData V4

3. Generador para Consistencia

Incluso en desarrollo manual: Use el generador una vez para ver la estructura esperada - luego puede replicar consistentemente.

4. Usar Control de Versiones

Commit inmediatamente después de cada generación - así puede rastrear cambios:

Terminal window
# Después de generación
git add .
git commit -m "feat: generated RAP BO for FlightBooking"
# Después de ajustes
git commit -m "feat: added validations and UI annotations"

Conclusión

Los generadores RAP ahorran tiempo considerable en la creación de aplicaciones estándar. La clave está en el uso correcto:

  1. Generador para estructura básica - Estructura y boilerplate
  2. Ajuste manual - Lógica de negocio y pulido de UI
  3. Enfoque iterativo - Generar, probar, ajustar

Para principiantes, sin embargo, se recomienda crear todos los objetos manualmente una vez - así entiende qué hace el generador en segundo plano. Después puede usar los generadores efectivamente.

Artículos Relacionados