Skip to Content

This blog post is part 2 of a series of blogs on how to develop full-stack To-Do application in SAP Web IDE Full-Stack.


Before reading this blog please make sure that you have read, understood and implemented part 0 and part 1 of this series.


Let’s Get Started!

Create your Java Module

The Java module is responsible for:

  1. OData provisioning of the database module
  2. Custom business logic

In our app we will use it for the OData provisioning.

To create the Java module, follow these steps:

  • In SAP Web IDE, select the todo project folder
  • Right-click it and select New -> Java Module
  • Select OData V4 Service Using SAP Cloud Platform SDK template and then click on Next.
  • Enter service as the module name and click Next.
  • Enter Group ID, artifact ID and package or just use the default values.
    Make sure that Enable SAP HANA Database support checkbox is checked! It’s needed to allow connectivity from the Java service to the HANA database module. Finally, click Finish.
  • SAP Web IDE creates a new service folder under your todo project folder. In addition, the mta.yaml file is updated and now contains the service java module in addition to the db module.
    Specifically notice the ‘provides’ and ‘requires’ sections in the mta.yaml file. The db and java modules both require HANA and provides a service_api which will be used by the UI module (that we will create in part 3 of this series).
  • Next, select the service folder which is located under service > src > main > java >
    {your_package_path} > service
  • Right-click it and select New > Java Class to create a new Java class
  • Enter ToDoService in the Name field, click Next and Finish
  • SAP Web IDE creates the file in the service folder
  • Open the file in the code editor
  • Copy the code below and paste it under the first line in the file (under the package {your_package_name} )
    import java.sql.Connection;
    import java.util.List;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
     * @author I059508
    public class ToDoService {
    	private static Logger logger = LoggerFactory.getLogger(ToDoService.class);
    	@Query(entity = "Task", serviceName = "todo")
    	public QueryResponse findTasks(QueryRequest request) {
    		try {
    			QueryResponse res = QueryResponse.setSuccess().setEntityData(getEntitySet(request)).response();
    			return res;
    		} catch (Exception e) {
    			return null;
    	@Read(entity = "Task", serviceName = "todo")
    	public ReadResponse getProposedBooks(ReadRequest readRequest){
    		try {
    			ReadResponse readResponse = ReadResponse.setSuccess().setData(readEntity(readRequest)).response();
    			return readResponse;
    		} catch (Exception e) {
    	       	return null;
    	private List<EntityData> getEntitySet(QueryRequest queryRequest) {
    		String fullQualifiedName = queryRequest.getEntityMetadata().getNamespace() + "." + queryRequest.getEntityMetadata().getName();			
    		CDSDataSourceHandler dsHandler = DataSourceHandlerFactory.getInstance().getCDSHandler(getConnection(), queryRequest.getEntityMetadata().getNamespace());
    		try {
    			CDSQuery cdsQuery = new CDSSelectQueryBuilder(fullQualifiedName).build();   		
    			CDSSelectQueryResult cdsSelectQueryResult = dsHandler.executeQuery(cdsQuery);			
    			return cdsSelectQueryResult.getResult();
    		} catch (Exception e) {
    			logger.error("==> Eexception while fetching query data from CDS: " + e.getMessage());
    		return null;
    	private EntityData readEntity(ReadRequest readRequest) throws Exception {
    		CDSDataSourceHandler dsHandler = DataSourceHandlerFactory.getInstance().getCDSHandler(getConnection(), readRequest.getEntityMetadata().getNamespace());
    		EntityData ed = dsHandler.executeRead(readRequest.getEntityMetadata().getName(), readRequest.getKeys(), readRequest.getEntityMetadata().getElementNames());
    		return ed;
    	private static Connection getConnection(){
    		Connection conn = null;
    		Context ctx;
    		try {
    			ctx = new InitialContext();
    			conn = ((DataSource) ctx.lookup("java:comp/env/jdbc/java-hdi-container")).getConnection();
    			System.out.println("conn = " + conn);
    		} catch (Exception e) {
    		return conn;


  • The java code that you just added is doing the following:
    • Connects to the SAP HANA database – see the getConnection() method
    • Uses the @Read and @Query annotations to expose a task and a list of tasks in OData. This is done using the SAP Cloud Java SDK which is added automatically by SAP Web IDE as a Maven dependency in the module (to understand more, review the pom.xml).

      Notice: This java code handles only the Task entity’s ‘query’ and ‘read’ operations.
      Handling the SubTask entity or any other CUD (create, update, delete) operations can be done in the same way (using the same SDK with similar code).


  • Now let’s create the EDMX file for our OData V4 service metadata.
    Select the edmx folder (which is located under the resources folder), right-click it and select New > File
  • Enter todo_v4_default.xml as the File Name and click OK
  • Open the new file and paste the following content into it:
    <?xml version='1.0' encoding='UTF-8'?>
    <edmx:Edmx Version="4.0" xmlns:edmx="">
    		<Schema xmlns="" Namespace="todo">
    			<EntityType Name="Task">
    					<PropertyRef Name="id"/>
    				<Property Name="id" Type="Edm.String" Nullable="false" MaxLength="10"/>
    				<Property Name="title" Type="Edm.String" Nullable="false" MaxLength="100"/>
    				<Property Name="note" Type="Edm.String" MaxLength="250"/>
    				<Property Name="status" Type="Edm.Int16"/>
    			<EntityType Name="SubTask">
    					<PropertyRef Name="id"/>
    				<Property Name="id" Type="Edm.String" Nullable="false" MaxLength="10"/>
            <Property Name="taskId" Type="Edm.String" Nullable="false" MaxLength="10"/>
    				<Property Name="content" Type="Edm.String" Nullable="false" MaxLength="250"/>
    				<Property Name="status" Type="Edm.Int16"/>
    			<EntityContainer Name="EntityContainer_16ED33654DD94D7FA71D8CBCD0F62216">
    				<EntitySet Name="Task" EntityType="todo.Task"></EntitySet>
            <EntitySet Name="SubTask" EntityType="todo.SubTask"></EntitySet>

    Notice – in the future this file will be automatically generated by SAP Web IDE and so this step will not be required anymore.
    Moreover, the EDMX file must be OData V4 complaint and must contain the same entities, properties and associations that we have in the HDBCDS file that was created in part 1 of this series. For the purpose of this blog it’s sufficient to just copy and paste it into your project.

Build and test your Java module

Now that we created all the relevant resources for our java module, its time to build it.
The build operation will execute a Maven build that will download all the dependencies and check that our java module is runnable.


  • Right-click the service folder (which is located under the todo folder) and click Build
  • Logs and info about the build status can be found in SAP Web IDE console (can be opened via the View menu bar).
  • The message Build of /todo/service completed successfully indicates that your project has been built successfully.
  • Now we can run the service!
    Right-click the service folder and select Run > Run Java Application
    (Notice this operation can take several minutes)
  • Finally, SAP Web IDE presents the service URL of your OData service in the Run Console
  • In order to view the content of the OData service, open your browser and enter the URL together with /odata/v4/todo appended to it.
    This should present the OData service document.
  • In order to access to the service metadata add /odata/v4/todo/$metadata
  • In order to access to the list of tasks add /odata/v4/todo/Task


That’s it 🙂

In part 3, we will show how to create the UI module that will consume this OData service.
Our app will consume the service and show the lists of tasks in a Master section, and the task details in a Details section.





To report this post you need to login first.


You must be Logged on to comment or reply to a post.

  1. Chaitanya Rayabharam

    Getting a error when i try to paste the code in the java class. Error says “import cannot be resolved”. This is happening will all import packages in the code. Can you suggest if I am missing something here

  2. Hanno Suijten

    Hi Ran, When creating the Java Module (step 1of this blog), I only have the following templates available

    It is not showing OData V4 Service Using SAP Cloud Platform SDK. How can I get this template?

    1. Michal Keidar


      Have you enabled all the features that were specified in part 0?
      Make sure that Tools for Java Development and the SAP S/4HANA Extension Tools features are enabled.


  3. Tri Le

    Hi Ran,

    Thanks for wonderful blogs.

    I have one question. It may be out of scope here.

    I see that when I choose new template, there is one option SAP S/4HANA Service Extension. How is this template different from MTA or Full stack application for CF?

    I’ve been trying to google document about it but found nothing.

    Do you have any resources regarding to this template?

    Thanks in advance.


    1. Ran Hassid Post author

      Hi Tri,

      My blogs explain how to create full stack app from scratch using our current programming model. The template that you asked about is for extending S/4 services (with code). I think Boris Tsirulnik can provide more info about it.



  4. Andreea Elisabeta Stoica

    Hi Ran,


    In a java module for an MTA project I need a library which is not part of the maven repository.

    I can find this library ( inside Nexus repository:

    I added a settings.xml file in the Java module with the nexus repository but still no success.

    In the documentation I’ve read that there is a default settings.xml file which is overwritten when you create your own settings file. See here:

    Could you tell me where can I find this default settings.xml file? Do I need to set any proxy for the nexus repository? Have any idea what I can do to solve my issue?

    Thank you!



  5. sarfaraz khan

    Hi Guys,

    nice blog and detailed to the best extent.

    i am trying out the same whereas when I run the service i dont get data in the response.

    the url that i hit is .-

    and response i get is – {“@odata.context”:”$metadata#Book”,”value”:[]} , ideally i should get the array of data from table.

    when i check logs i find that there is an java exception in line -conn = ((DataSource)

    “javax.naming.NamingException: The url cannot be null
    at org.apache.naming.NamingContext.lookup(”

    looks like it is not able to fetch the HDI containername or somethinng like that , i have no clue what this line of code means.

    might be i am missing on a ny steps of some setting to be done in full stack webide.

    any help here is highly appreciated.







    1. Ran Hassid Post author

      Hi, this blog shows how to create ToDo app and your URL points to the Book entity so i wanted to know if you are trying to create a different app?

    1. Ran Hassid Post author

      Hi , sorry for the delay in my response.

      I think this is related to the Java class. Can you please share your Java class (the




  6. Prajakta Sambre

    When I try to run Java Application, getting following error-

    Running module todo/service failed. Cannot read property “Report” of undefined.


    With oData service, getting metadata correctly. But when I try to read data using Task entity, it returns empty data-

    Can someone please help? 
    Also, I am putting breakpoints in Java App, but they never seem to get hit. Any particular way to run the app in debug mode?
    1. Ran Hassid Post author

      Hi, Did you tried to check if you get any issue in the database explorer? Please make sure this feature is enabled before doing it


Leave a Reply