SAPUI5: How can I access ODataModel data programatically?

Mario picture Mario · Aug 3, 2016 · Viewed 10.1k times · Source

When I create a model in code, I usually use:

var oData = {
  "name" : "",
  "description" : "",
  "phone" : ""
};
var oModel = new JSONModel(oData);
this.setModel(oModel, "data");

After that, I can access to the model and it's values using:

var oModel = this.getView().getModel("data");
var description = oModel.getProperty("/description");

But, that is using an internal json structure. How can I get the oModel structure when I use a oData destination from Hana Platform or when I use a mockup-server on my SAPUI5 project?

Answer

cschuff picture cschuff · Aug 4, 2016

The getProperty method exists on an ODataModel (v2) as on any other model. Hence the usage differs a lot:

How ODataModel stores data

This is because the ODataModel stores data by it's keys, e.g.

{
  "EntitySet('Key-1')": {},
  "EntitySet('Key-2')": {},
  "EntitySet('Key-3')": {},
  "ExpandedEntitySet(EntityID='Key-3',ExpandedEntityIS='5')": {}
}

Check oMyODataDataModel.oData to see the actual stored data (but please do not use or manipulate it this way since this is internal API).

ODataModels getProperty

To retrieve a single entity you would have to say something like:

oDataModel.getProperty("/EntitySet('Key-1')");

Eventhough the binding path for the collection is /EntitySet requesting

oDataModel.getProperty("/EntitySet");

would return nothing. This happens because there is no entity in the internally stored data structure for oData["EntitySet"] and the getProperty method is still nothing else then a look-up in this internal structure.

Include expanded entities

One interesting thing with ODataModels getProperty method is the bIncludeExpandEntries parameter. If you set it to true the accessed entity will be returned including all potentially expanded NavigationProperties. In the above example

oDataModel.getProperty("/EntitySet('Key-3')");

will also return "ExpandedEntitySet(EntityID='Key-3',ExpandedEntityIS='5')" with it.

ODataModels getObject

ODataModels getObject method has a lot more flexibility since it allows for the local use of the OData parameters $select and $expand. Getting an EntitySet is still not possible... NOTE: It will not load any missing data and the returned data may be incomplete!