You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供ODataCreate/Update/DeleteRequestBuilder使用示例及CSRF令牌处理方案

SAP Cloud SDK OData V2: Create/Update/Delete Request Builders + CSRF Handling Examples

Got it, let's walk through practical, runnable examples for using ODataCreateRequestBuilder, ODataDeleteRequestBuilder, and ODataUpdateRequestBuilder from the com.sap.cloud.sdk.odatav2.connectivity package, plus a deep dive into how CSRF tokens are handled. All code is ready to use with proper setup.


Prerequisites

First, make sure you have:

  • Generated OData entity classes (use the SAP Cloud SDK OData Generator for your target service, e.g., BusinessPartner for the S/4HANA Business Partner API)
  • A configured DefaultErpHttpDestination (either from Cloud Foundry environment variables, local default-env.json, or manual setup)

1. ODataCreateRequestBuilder (Create Operation)

This handles creating new entities via POST requests. The SDK automatically manages CSRF tokens for you.

import com.sap.cloud.sdk.odatav2.connectivity.ODataCreateRequestBuilder;
import com.sap.cloud.sdk.odatav2.connectivity.ODataRequestExecutionResult;
import com.sap.cloud.sdk.s4hana.connectivity.DefaultErpHttpDestination;
import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner;

public BusinessPartner createBusinessPartner(DefaultErpHttpDestination destination) throws Exception {
    // 1. Build your entity with the required data
    BusinessPartner newPartner = BusinessPartner.builder()
        .businessPartnerCategory("1") // Individual customer
        .firstName("John")
        .lastName("Doe")
        .build();

    // 2. Construct the create request
    ODataCreateRequestBuilder createRequest = new ODataCreateRequestBuilder(
        destination,
        BusinessPartner.ENTITY_SET_NAME,
        newPartner
    )
    // Optional: Select specific fields to return after creation (reduces payload)
    .select(BusinessPartner.BUSINESS_PARTNER, BusinessPartner.FIRST_NAME, BusinessPartner.LAST_NAME);

    // 3. Execute the request (CSRF token is handled automatically)
    ODataRequestExecutionResult result = createRequest.execute();

    // 4. Parse the response back to your entity class
    return result.as(BusinessPartner.class);
}

2. ODataUpdateRequestBuilder (Update Operation)

Use this for modifying existing entities. By default, it uses MERGE (PATCH) for partial updates, but you can switch to PUT for full updates.

import com.sap.cloud.sdk.odatav2.connectivity.ODataUpdateRequestBuilder;
import com.sap.cloud.sdk.s4hana.connectivity.DefaultErpHttpDestination;
import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner;

public BusinessPartner updateBusinessPartner(String partnerId, String newLastName, DefaultErpHttpDestination destination) throws Exception {
    // 1. Create an entity instance with the key and updated fields
    BusinessPartner updatedPartner = BusinessPartner.builder()
        .businessPartner(partnerId) // Mandatory: entity key to identify the record
        .lastName(newLastName)
        .build();

    // 2. Build the update request
    ODataUpdateRequestBuilder updateRequest = new ODataUpdateRequestBuilder(
        destination,
        BusinessPartner.ENTITY_SET_NAME,
        updatedPartner
    )
    // Optional: Switch to PUT for full entity replacement (default is MERGE/PATCH)
    // .withHttpMethod(HttpMethod.PUT)
    .select(BusinessPartner.BUSINESS_PARTNER, BusinessPartner.LAST_NAME);

    // 3. Execute (CSRF token handled automatically)
    ODataRequestExecutionResult result = updateRequest.execute();

    return result.as(BusinessPartner.class);
}

3. ODataDeleteRequestBuilder (Delete Operation)

This handles deleting entities by their key value.

import com.sap.cloud.sdk.odatav2.connectivity.ODataDeleteRequestBuilder;
import com.sap.cloud.sdk.s4hana.connectivity.DefaultErpHttpDestination;
import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner;

public void deleteBusinessPartner(String partnerId, DefaultErpHttpDestination destination) throws Exception {
    // 1. Build the delete request using the entity set and key
    ODataDeleteRequestBuilder deleteRequest = new ODataDeleteRequestBuilder(
        destination,
        BusinessPartner.ENTITY_SET_NAME,
        partnerId // Key value of the entity to delete
    );

    // 2. Execute (CSRF token handled automatically)
    deleteRequest.execute();
}

CSRF Token Handling Explained

For all modifying operations (POST/PUT/PATCH/DELETE), the SAP Cloud SDK OData V2 library automatically manages CSRF tokens:

  1. It first sends a HEAD request to the OData service's entity set (or a custom path you define) to fetch the X-CSRF-Token from the response headers.
  2. It includes this token in the subsequent modifying request's X-CSRF-Token header.

Custom CSRF Configuration

  • If your service requires a specific path to retrieve the CSRF token, use:
    createRequest.withCsrfTokenRetrievalPath("/sap/opu/odata/sap/API_BUSINESS_PARTNER/$metadata");
    
  • If your service doesn't require CSRF tokens (not recommended for production), disable automatic handling:
    createRequest.disableCsrfTokenRetrieval();
    

Full Runnable Example

Combine all operations into a single class, including destination retrieval:

import com.sap.cloud.sdk.cloudplatform.connectivity.DestinationAccessor;
import com.sap.cloud.sdk.s4hana.connectivity.DefaultErpHttpDestination;
import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner;

public class ODataCrudDemo {
    public static void main(String[] args) {
        try {
            // Retrieve your configured destination (name matches your setup)
            DefaultErpHttpDestination destination = DestinationAccessor.getDestination("S4HANA_DEST")
                .asHttp()
                .decorate(DefaultErpHttpDestination::new);

            ODataCrudDemo demo = new ODataCrudDemo();

            // 1. Create a new business partner
            BusinessPartner createdPartner = demo.createBusinessPartner(destination);
            System.out.println("Created Partner: " + createdPartner.getBusinessPartner() + " - " + createdPartner.getFirstName() + " " + createdPartner.getLastName());

            // 2. Update the partner's last name
            BusinessPartner updatedPartner = demo.updateBusinessPartner(createdPartner.getBusinessPartner(), "Smith", destination);
            System.out.println("Updated Partner: " + updatedPartner.getBusinessPartner() + " - " + updatedPartner.getLastName());

            // 3. Delete the partner
            demo.deleteBusinessPartner(createdPartner.getBusinessPartner(), destination);
            System.out.println("Partner deleted successfully");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Include the create, update, delete methods from the sections above here
}

Note: Replace "S4HANA_DEST" with your actual destination name. For local development, configure the destination in a default-env.json file.

内容的提问来源于stack exchange,提问作者user3170440

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:45:28