Instantiating an OData Model

The OData Model enables binding of controls to data from OData services.

The OData model is a server-side model, meaning that the dataset is only available on the server and the client only knows the currently visible (requested) data. Operations, such as sorting and filtering, are done on the server. The client sends a request to the server and shows the returned data.

The OData model currently supports OData version 2.0.

The following two versions of the OData model are implemented: sap.ui.model.odata.ODataModel and sap.ui.model.odata.v2.ODataModel. The v2.ODataModel has an improved feature set and new features will only be implemented in this model. sap.ui.model.odata.ODataModel is deprecated. We recommend to only use v2.ODataModel.

The following table shows the supported features for both OData models:

Feature

sap.ui.model.odata.v2.ODataModel

sap.ui.model.odata.ODataModel

OData version support

2.0

2.0

JSON format

Yes (default)

Yes

XML format

Yes

Yes (default)

Support of two-way binding mode

Yes; for property changes only, not yet implemented for aggregations

Experimental; only properties of one entity can be changed at the same time

Default binding mode

One-way binding

One-way binding

Client-side sorting and filtering

Yes; see sap.ui.model.odata.OperationMode in the API reference

No

$batch

Yes; all requests can be batched

Only manual batch requests are possible

Data cache in model

All data is cached in the model

Manually requested data is not cached

Automatic refresh

Yes (default)

Yes

Message handling

Yes, see Managing UI and Server Messages

No

Note

Be aware of the Same-Origin-Policy security concept which prevents access to backends on different domains or sites.

The requests to the service to fetch data are made automatically based on the data bindings that are defined for the controls.

Creating the Model Instance

One OData model instance can only cover one OData service. For accessing multiple services, you have to create multiple OData model instances. The only mandatory parameter when creating an ODataModel instance is the service URL. It can be passed as first parameter or within the mParameters map to the constructor.

#!jsvar oModel = new sap.ui.model.odata.v2.ODataModel("http://services.odata.org/Northwind/Northwind.svc/");
var oModel = new sap.ui.model.odata.v2.ODataModel({serviceUrl: "http://services.odata.org/Northwind/Northwind.svc"});

When creating an ODataModel instance, a request is sent to retrieve the service metadata:

http://services.odata.org/Northwind/Northwind.svc/$metadata
Service Metadata

The service metadata is cached per service URL. Multiple OData models that are using the same service can share this metadata. Only the first model instance triggers a $metadata request. A JSON representation of the service metadata can be accessed by calling the getServiceMetadata() method on an Odata model instance.

#!js
var oMetadata = oModel.getServiceMetadata();
Note

In the v2.ODataModel, the service metadata is loaded asynchronously. It is not possible to load it synchronously. To get notified when the loading is finished, attach the metadataLoaded event.

Adding Additional URL Parameters

For OData services, you can use URL parameters for configuration. SAPUI5 sets most URL parameters automatically, according to the respective binding.

For authentication tokens or general configration options, for example, you can add additional arguments to the request URL. Some of the parameters must not be included in every request, but should only be added to specific aggregation or element bindings, such as $expand or $select. For this, the binding methods provide the option to pass a map of parameters, which are then included in all requests for this specific binding. The OData model currently only supports $expand and $select.

There are different ways to add URL parameters to the requests:

  • Appending parameters to the service URL:

    #!jsvar oModel = new sap.ui.model.odata.v2.ODataModel("http://myserver/MyService.svc/?myParam=value&myParam2=value");

    These parameters will be included in every request sent to the OData server.

  • Passing URL parameters with the mparameters map

    You can pass URL parameters that are used for $metadata requests only (metadataUrlParams) as well as URL parameters that are included only in data requests (serviceUrlParams). The parameters are passed as maps:

    #!jsvar oModel = new sap.ui.model.odata.v2.ODataModel({ 
        serviceUrl: "http://services.odata.org/Northwind/Northwind.svc",    
        serviceUrlParams: {
            myParam: "value1",
            myParam2: "value2"
        },
        metadataUrlParams: {
            myParam: "value1",
            myParam2: "value2"
        }
    });
Custom HTTP Headers

You can add custom headers which are sent with each request. To do this, provide a map of headers to the OData model constructor or use the setHeaders() function:

  • Passing custom headers with the mparameters map

    #!jsvar oModel = new sap.ui.model.odata.v2.ODataModel({
        headers: {
            "myHeader1" : "value1",
            "myHeader2" : "value2"
        }
    });
  • Setting custom headers globally on a model instance

    #!js
    oModel.setHeaders({"myHeader1" : "value1", "myHeader2" : "value2"});
    Note

    When you add custom headers, all previous custom headers are removed if not specified again in the headers map. Some headers are private, that is, they are set by the OData model internally and cannot be set:

    "accept"
    "accept-language"
    "maxdataserviceversion"
    "dataserviceversion"
    "x-csrf-token"

    For additional methods and parameters, see sap.ui.model.odata.v2.ODataModel.

Addressing Entities: Binding Path Sytnax

The binding path syntax for OData models matches the URL path relative to the service URL used in OData to access specific entities or entity sets.

You access the data provided by the OData model according to the structure of the OData service as defined in the metadata of a service. URL parameters, such as filters, cannot be added to a binding path. A binding path can be absolute or relative. Absolute binding paths are resolved immediately. A relative path can only be resolved if it can be automatically converted into an absolute binding path. If, for example, a property is bound to a relative path and the parent control is then bound to an absolute path, the relative property path can e resolved to an absolute path.

The following binding samples within the ODataModel are taken from the Northwind demo service.

Absolute binding path (starting with a slash ('/')):

"/Customers"
"/Customers('ALFKI')/Address"

Relative binding paths that can be resolved with a context (for example "/Customer('ALFKI')"):

"CompanyName"
"Address"
"Orders"

Resolved to:

"/Customer('ALFKI')/CompanyName"
"/Customer('ALFKI')/Address"
"/Customer('ALFKI')/Orders"

Navigation properties, used to identify a single entity or a collection of entities:

"/Customers('ALFKI')/Orders"
"/Products(1)/Supplier"

For more information on addressing OData entries, see the URI conventions documentation on http://www.odata.orgInformation published on non-SAP site.

Accessing Data from an OData Model

The data requested from an OData service is cached in the OData model. It can be accessed by the getData() and the getProperty() method, which returns the entity object or value. These methods do not request data from the backend, so you can only access already requested and cached entities:

#!jsoModel.getData("/Customer('ALFKI')");
oModel.getProperty("/Customer('ALFKI')/Address");

You can only access single entities and properties with these methods. To access entity sets, you can get the binding contexts of all read entities via a list binding. The values returned by these methods are copies of the data in the model, not references as in the JSONModel.

Caution

Do not modify objects or values inside the model manually; always use the provided API to change data in the model, or use two-way binding (see Two-way Binding section below).

Creating Entities

To create entities for a specified entity set, call the createEntry() method. The method returns a context object that points to the newly created entity. The application can bind against these objects and change the data by means of two-way binding. To store the entities in the OData backend, the application calls submitChanges(). To reset the changes, the application can call the deleteCreatedEntry() method.

The application can choose the properties that shall be included in the created object and can pass its own default values for these properties. Per default, all property values are be empty, that is, undefined.

Note

The entity set and the passed properties must exist in the metadata definition of the OData service.

// create an entry of the Products collection with the specified properties and values
var oContext = oModel.createEntry("Products", { ID:99, Name:"Product", Description:"new Product", ReleaseDate:new Date(), Price:"10.1", Rating:1});
// binding against this entity
oForm.setBindingContext(oContext);
// submit the changes (creates entity at the backend)
oModel.submitChanges({success: mySuccessHandler, error: myErrorHandler});
// delete the created entity
oModel.deleteCreatedEntry(oContext);

If created entities are submitted, the context is updated with the path returned from the creation request and the new data is imported into the model. So the context is still valid and points to the new created entity.

CRUD Operations

The OData model allows manual CRUD (create, read, update, delete) operations on the OData service. If a manual operation returns data, the data is imported into the data cache of the OData model. All operations require a mandatory sPath parameter as well as an optional mParameters map. The create and update methods also require a mandatory oData parameter for passing the created or changed data object. Each operation returns an object containing a function abort, which can be used to abort the request. If the request is aborted, the error handler is called. This ensures that the success or the error handler is executed for every request. It is also possible to pass additional header data, URL parameters, or an eTag.

  • Creating entities

    The create function triggers a POST request to an OData service which was specified at creation of the OData model. The application has to specify the entity set, in which the new entity and the entity data is to be created.

    #!jsvar oData = {
        ProductId: 999,
        ProductName: "myProduct"
    }
    oModel.create("/Products", oData, {success: mySuccessHandler, error: myErrorHandler});
  • Reading entities

    The read function triggeres a GET request to a specified path. The path is retrieved from the OData service which was specified at creation of the OData model. The retrieved data is returned in the success callback handler function.

    #!jsoModel.read("/Products(999)", {success: mySuccessHandler, error: myErrorHandler});
  • Updating entities

    The update function triggers a PUT/MERGE request to an OData service which was specified at creation of the OData model. After a successful request to update the bindings in the model, the refresh is triggered automatically.

    #!js
    var oData = {
        ProductId: 999,
        ProductName: "myProductUpdated"
    }
    oModel.update("/Products(999)", oData, {success: mySuccessHandler, error: myErrorHandler});
  • Deleting entities

    The remove function triggers a DELETE request to an OData service which was specified at creation of the OData model. The application has to specify the path to the entry which should be deleted.

    #!jsoModel.remove("/Products(999)", {success: mySuccessHandler, error: myErrorHandler});
  • Refresh after change

    The model provides a mechanism to automatically refresh bindings that depend on changed entities. If you carry out a create, update or remove function, the model identifies the bindings and triggers a refresh for these bindings. If the model runs in batch mode, the refresh requests are bundled together with the changes in the same batch request. You can disable the auto refresh by calling setRefreshAfterChange(false). If the auto refresh is disabled, the application has to take care of refreshing the respective bindings.

    #!jsoModel.setRefreshAfterChange(false);
Concurrency Control and ETags

OData uses HTTP ETags for optimistic concurrency control. The service must be configured to provide them. The ETag can be passed within the parameters map for every CRUD request. If no ETag is passed, the ETag of the cached entity is used, if it is loaded already.

XSFR Token

To address cross-site request forgery, an OData service may require XSRF tokens for change requests by the client application. In this case, the client has to fetch a token from the server and send it with each change request to the server. The OData model fetches the XSRF token when reading the metadata and then automatically sends it with each write request header. If the token is no longer valid, a new token can be fetched by calling the refreshSecurityToken function on the OData model. The token is fetched with a request to the service document. To ensure getting a valid token, make sure that the service document is not cached.

Refreshing the Model

The refresh function refreshes all data within an OData model. Each binding reloads its data from the server. For list or element bindings, a new request to the backend is triggered. If the XSRF token is no longer valid, it has to be fetched again with a read request to the service document. Data that has been imported via manual CRUD requests is not reloaded automatically.

Batch Processing

The v2.ODataModel supports batch processing ($batch) in two different ways:

  • Default: All requests in a thread are collected and bundled in batch requests, meaning that request is sent in a timeout immediately after the current call stack is finished. This includes all manual CRUD requests as well as requests triggered by a binding.

  • The requests are stored and can be submitted with a manual submitChanges() call by the application. This also includes all manual CRUD requests as well as requests triggered by a binding.

The model cannot decide how to bundle the requests. For this, SAPUI5 provides the batchGroupId. For each binding and each manual request, a batchGroupId can be specified. All requests belonging to the same group are bundled into one batch request. Request without a batchGroupId are bundled in the default batch group. You can use a changeSetId for changes. The same principle applies: Each change belonging to the same changeSetId is bundled into one changeSet in the batch request. Per default, all changes have their own changeSet. For more information, see the API reference.

You can use the the setDeferredBatchGroups() method to set each batchGroup to deferred: All requests belonging to the batchGroup are then stored in a request queue. The deferred batch group must then be submitted manually by means of the submitChanges() method. If you do not specify a batch group ID when calling submitChanges, all deferred batch groups are submitted.

Example:

#!jsvar oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl);

Pass the batchGroupId to a binding:

#!js{path:"/myEntities", parameters: {batchGroupId: "myId"}}

Set the batchGroupId to deferred:

#!jsoModel.setDeferredBatchGroups(["myGroupId", "myGroupId2"]);

Submit a deferred batchGroup:

#!jsoModel.submitChanges({batchGroupId: "myGroupId", success: mySuccessHandler, error: myErrorHandler});
Two-way Binding

The v2.ODataModel enables two-way binding. Per default, all changes are collected in a batch group called "changes" which is set to deferred. To submit the changes, use submitChanges(). The data changes are made on a data copy. This enables you to reset the changes without sending a new request to the backend to fetch the old data again. With resetChanges() you can reset all changes. You can also reset only specific entities by calling resetChanges with an array of entity paths.

Note

Filtering and sorting is not possible if two-way changes are present as this would cause inconsistent data on the UI. Therefore, before you carry out sorting or filtering, you have to submit or reset the changes.

You can collect the changes for different entities or types in different batch groups. To configure this, use the setChangeBatchGroups() method of the model:

#!jsvar oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl);
oModel.setDeferredBatchGroups(["myGroupId", "myGroupId2"]);
oModel.setChangeBatchGroups({
    "EntityTypeName": {
        batchGroupId: "myGroupId",  
        [changeSetId: "ID",]
        [single: true/false,]
    }
);
oModel.submitChanges({batchGroupId: "myGroupId", success: mySuccessHandler, error: myErrorHandler});

To collect the changes for all entity types in the same batch group, use '*’ as EntityType. If the change is not set to deferred, the changes are sent to the backend immediately. By setting the single parameter for changeSet to true or false, you define if a change is assigned its own change set (true) or if all changes are collected in one change set (false). The model only takes care of the changeSetId if single is set to false.

Note

The first change of an entity defines the order in the change set.

Example

Reset changes:

#!jsvar oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl);
//do a change
oModel.setProperty("/myEntity(0)", oValue);

//reset the change
oModel.resetChanges(["/myEntity(0)"]);
Binding-specific Parameters

The OData protocol specifies different URL parameters. You can use these parameters in bindings in addition to the parameters described above:

  • Expand parameter

    The expand parameter allows the application to read associated entities with their navigation properties:

    #!jsoControl.bindElement("/Category(1)", {expand: "Products"}); 
    
    oTable.bindRows({
        path: "/Products",
        parameters: {expand: "Category"}
    });

    In this example, all products of "Category(1)" are embedded inline in the server response and loaded in one request. The category for all "Products" is embedded inline in the response for each product.

  • Select parameter

    The select parameter allows the application to define a subset of properties that is read when requesting an entity.

    #!jsoControl.bindElement("/Category(1)", {expand: "Products", select: "Name,ID,Products"}); 
    
    oTable.bindRows({
        path: "/Products",
        parameters: {select: "Name,Category"}
    });

    In this example, the properties Name, ID and ofCategory(1) as well as all properties of the embedded products are returned. The properties Name and Category are included for each product. The Category property contains a link to the related category entry.

  • Custom query options

    You can use custom query options as input parameters for service operations. When creating the aggregation binding, specify these custom parameter as follows:

    #!jsoTable.bindRows({
            path: "/Products", 
            parameters: {
            custom: {
                param1: "value1",
                param2: "value2"
            }
        },
        template: rowTemplate
    });

    If you use bindElement, you can specify custom parameters as follows:

    #!jsoTextField.bindElement("/GetProducts", {
        custom: {
            "price" : "500"
        }
    });
Function Import
The ODataModel supports the invoking of function imports or actions by the callFunction method:
#!xmloModel.callFunction("/GetProductsByRating",{method:"GET", urlParameters:{"rating":3}, success:fnSuccess, error: fnError})
If the callFunction request is deferred, it can be submitted via the submitChangesmethod.
Note

Only "IN" parameters of function imports are currently supported.

Binding of Function Import Parameters
As of SAPUI5 version 1.34.2, the OData Model V2 supports the binding against function import parameters. This is similar to the createEntry method which supports binding against entity properties. The callFunction method returns a request handle that has a promise. This promise is resolved when the context to which it is bound is created successfully or is rejected if not:
#!xmlvar oHandle = oModel.callFunction("/GetProductsByRating", {urlParameters: {rating:3}});
oHandle.contextCreated().then(function(oContext) {
      oView.setBindingContext(oContext);
});
If the function import returns result data, then the result data can be accessed and bound against in the $result property using the context:
#!xml<form:SimpleForm>
   <core:Title text="Parameters" />
   <Label text="Rating" />
   <Input value="{rating}" />
   <Button text="Submit" press=".submit" />
   <core:Title text="Result" />
   <List items="{$result}">
    <StandardListItem title="{Name}" />
   </List>
</form:SimpleForm>