Create a Reusable Service
Create a service that will later on be reused in another CAP Java project.
Overview
You will learn
- How to write an entity definition
- How to use some generic CAP artifacts like aspects and types
- What associations and compositions are
- How to make the project reusable The previous tutorial was about quickly setting up a working CAP application and read/write some mock data. This tutorial is about learning how to extend the application to a complete products service. You will take advantage of many of the out-of-the-box features provided by the CAP Java SDK such as using H2 as a database for local development. As a result, you will remove your custom handlers written in the first tutorial. In subsequent tutorials you will swap out H2 with the SAP HANA service, when preparing your application for the cloud.
Prerequisites
Steps
In the previous tutorial, you defined a service, which defined its own entity. When modeling with CDS the best practice is to separate services from the domain model.
Therefore, you will now define the complete domain model that is used by the products service. The domain model is stored in the db folder of your CAP application.
Go to your
dbfolder and create a file calledschema.cds.
schema cds file creation Add the following code to your newly created
schema.cdsfile and make sure you Save the file:CDSnamespace sap.capire.products; using { Currency, cuid, managed, sap.common.CodeList } from '@sap/cds/common'; entity Products : cuid, managed { title : localized String(111); descr : localized String(1111); stock : Integer; price : Decimal(9,2); currency : Currency; category : Association to Categories; } entity Categories : CodeList { key ID : Integer; parent : Association to Categories; children : Composition of many Categories on children.parent = $self; }
As you can see, the domain model defines two entities:
ProductsCategories
It also imports various common definitions from the @sap/cds/common package (a globally available reuse package):
CurrencycuidmanagedCodeList
In addition, the domain model uses the CDS keywords localized, Association , and Composition. Let’s explain these imports and keywords in more detail:
The localized keyword can be used to mark elements, which require translation. The ability to store translations for different languages and to store a default fallback translation is automatically handled by CDS for you. You will see this in action in more detail in the next tutorial.
Associations and compositions can be used to define relationships between entities. They often allow you to define these relationships without explicitly working with foreign keys.
While associations define a rather loose coupling between the entities, compositions define a containment relationship. Compositions can also be thought of as defining deep structures. You can perform deep inserts and upserts along these structures.
In your domain model, the Categories entity defines a parent and children element. This enables a hierarchy of categories. The children of a category are modelled as a composition. A category with all of its children defines a deep nested structure. Deleting a category would automatically delete all of its children. However, the parent of a category is modelled as an association. Deleting a category obviously shouldn’t delete its parent.
Both cuid and managed are aspects. Aspects extend an entity with additional elements. The cuid aspect adds a key element ID of type UUID to the entity.
The managed aspect adds four additional elements to the entity. These capture the time of the creation and last update of the entity, and the user, which performed the creation and last update.
CodeLists can be used to store global, translatable definitions based on codes, such as currencies, countries, or languages. Especially for UIs, a CodeList can be useful to provide a value help for certain input fields.
The Currency definition is a type. It defines an association to a Currencies entity. The Currencies entity is based on ISO 4217 and uses three-letter alpha codes as keys such as EUR or USD and provides the possibility to store the corresponding currency symbol such as € or $.
Look at these explained keywords yourself and learn more about it.
To jump to the imported definitions directly in your editor, press
CTRL, hover over the keyword, and click. This will open the source file in a separate editor tab.Hold
CTRLand hover over a keyword, then move the hand cursor over the keyword. This opens up you a tiny overlay with the definition of this particular item.
overlay of definition A right-click (or use
F12) on the definition opens up the context menu. There you can find, for example, Peek definition to get a much bigger overlay. Not only the definition of this particular item is displayed, you also have the ability to navigate through the whole source file of this definition without opening the file itself.
right-click to peek definition information
In the first tutorial, you defined a simple service, called AdminService, which directly defined the entity Products. As you now have defined the Products entity in your domain model, the AdminService just needs to expose it. In addition, you defined the Categories entity, which should also be part of your service.
This can be achieved by using projections. Services expose projections of the entities defined in the domain model. These projections can be used to include (and also exclude) only certain elements of an entity or to rename the entity’s elements.
In this example you will use the most simple projection, which exposes the domain model entity without any changes.
Go to your
srvfolder and open theadmin-service.cdsfile.Replace the content with the following code and make sure you Save the file:
CDSusing { sap.capire.products as db } from '../db/schema'; service AdminService { entity Products as projection on db.Products; entity Categories as projection on db.Categories; }
The CAP Java SDK provides out-of-the-box capabilities to store and retrieve entities from a database. Therefore, no custom coding is required if entities are stored in the database. The entities defined in your AdminService will be automatically served via OData and you can just delete the AdminService.java file that was created earlier.
- Delete the
AdminService.javafile in thehandlersfolder.
By default, the CAP Java SDK uses an in-memory H2 database. The content of this database will be lost when the application is stopped.
In case you need a persistent database between application runs you can use a file-based SQLite database as described in section Using Databases in the CAP documentation.
Stop your application if it is still running. Now restart your application by running
mvn spring-boot:runin the terminal and open it in a new tab.You will now create some
Categoriesthrough a HTTP request. Add the following request to therequests.httpfile you have created earlier by pasting the following content:HTTP### Create Categories POST http://localhost:8080/odata/v4/AdminService/Categories Content-Type: application/json {"ID": 1, "name": "TechEd", "descr": "TechEd related topics", "children": [{"ID": 10, "name": "CAP Java", "descr": "Run on Java"}, {"ID": 11, "name": "CAP Node.js", "descr": "Run on Node.js"}]}Choose
Send Requestwhich appears over the new request. This request will create multiple, nested categories, at once through a deep insert.Try to query individual categories, for example by adding the following to the end of your app URL:
/odata/v4/AdminService/Categories(10)You can also expand the nested structures. Add the following to the end of your app URL:
/odata/v4/AdminService/Categories?$expand=children/odata/v4/AdminService/Categories(10)?$expand=parent/odata/v4/AdminService/Categories(1)?$expand=children
Make sure to stop your application after testing it by using
CTRL+C.
In the following tutorial, the application will be reused by a bookstore application. The reuse of models can be achieved by publishing NPM modules with the models and defining dependencies to these NPM modules in other applications. There are a two steps we need to perform to prepare the products-service application for reuse.
The name of the
products-servicereuse module, should be@sap/capire-products. Therefore, open thepackage.jsonfile within the~/projects/products-servicefolder and change the value ofnamefield fromproducts-service-cdsto@sap/capire-products. If you want to you can also provide a meaningful description in thedescriptionfield.
adjust the package.json in the root folder of your project To make it easier to reuse the module, an
index.cdsfile can be added to theproducts-service. This ensures a better decoupling from other applications. Create a new fileindex.cdsin the~/projects/products-servicefolder and place the following content inside this file, making sure you Save the file:CDSusing from './db/schema'; using from './srv/admin-service';
Congratulations! You have successfully developed the products service application, which is based on a CDS domain model and service definition.
In the next tutorial, you will build a bookstore application, reusing the products service application. You will later extend the bookstore application with custom business logic and deploy it to the cloud, using SAP HANA as the database.
Resources
Discussion
Share feedback on this tutorial or join the conversation in SAP Community.