The ServiceLayer

When implementing new business logic, you separate the business code into java classes called services. Each service implements a specific, well-defined requirement.

Services form part of the ServiceLayer. This layer is a logical tier between the client and persistence layer. Each service has its own java interface that lists the public methods that can be called by clients and other services.

A service may contain all required business logic, but more commonly will delegate to one or more of the following:

  • Other services providing part of the behavior required
  • Strategy objects that provide swappable behavior for different requirements, e.g. different cart calculation algorithms
  • Data access objects that handle locating and retrieving data items from the database

These other services, strategy objects and data access objects are also defined as Spring beans, with respective interfaces and implementations.

To build your service, you create the following files in the src folder of the concerttours extension:

  • BandDAO: The DAO interface, which describes the CRUD functionality that you require, in this case only read functionality.
  • DefaultBandDAO: The DAO implementation
  • BandService: The band service interface
  • DefaultBandService: The band service implementation

Extend the ServiceLayer

Add new functionality to your extension to list and find Bands by adding a new service interface, service implementation, and supporting DAOs.

Prerequisites

The following acceptance test is included in your Hybris123Tests.java file.
public void testServiceLayerClassesExist() throws IOException {
  // If you have correctly added an extension there should be some new folders and files
  assertTrue("You should have added concerttours.daos.BandDAO.java", FileHelper.fileExistsAndContains(
      "../hybris/bin/custom/concerttours/src/concerttours/daos/BandDAO.java", "public interface BandDAO"));
  assertTrue("You should have added concerttours.daos.impl.DefaultBandDAO.java", FileHelper.fileExistsAndContains(
      "../hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultBandDAO.java", "public class DefaultBandDAO implements BandDAO"));
  assertTrue("You should have modified concerttours-spring.xml", FileHelper.fileExistsAndContains(
      "../hybris/bin/custom/concerttours/resources/concerttours-spring.xml", "<context:component-scan base-package=\"concerttours\"/>"));
  assertTrue("You should have added concerttours.service.impl.DefaultBandService.java", FileHelper.fileExistsAndContains(
      "../hybris/bin/custom/concerttours/src/concerttours/service/impl/DefaultBandService.java", "public class DefaultBandService implements BandService"));
  assertTrue("You should have added concerttours.service.BandService.java", FileHelper.fileExistsAndContains(
      "../hybris/bin/custom/concerttours/src/concerttours/service/BandService.java", "public interface BandService"));
  }
Before you begin this step, run the test to confirm that it fails by executing this command:
cd $HYBRIS_HOME_DIR/hybris123; mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testServiceLayerClassesExist test
cd %HYBRIS_HOME_DIR%\hybris123 & mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testServiceLayerClassesExist test

Procedure

  1. Stop SAP Commerce Cloud.
    cd $HYBRIS_HOME_DIR/hybris/bin/platform; ./hybrisserver.sh stop
    cd %HYBRIS_HOME_DIR%\hybris\bin\platform & hybrisserver.bat stop
  2. Create a new BandDAO DAO interface under the concerttours extension's src/concerttours/daos folder.
    package concerttours.daos;
    import java.util.List;
    import concerttours.model.BandModel;
     
    /**
     * An interface for the Band DAO including various operations for retrieving persisted Band model objects
     */
    public interface BandDAO
    {
        /**
         * Return a list of band models that are currently persisted. If none are found an empty list is returned.
         *
         * @return all the bands in the system
         */
        List<BandModel> findBands();
        /**
         * Finds all bands with given code. If none is found, an empty list will be returned.
         *
         * @param code
         *           the code to search for bands
         * @return All bands with the given code.
         */
        List<BandModel> findBandsByCode(String code);
    }
    • The interface consists of methods required by the test DefaultBandDAOIntegrationTest.java.
    • The comments describe the behavior for both success and failure of each method.
    • You do not need a save method. The saving mechanism is done by modelService.
    • findBandsByCode returns a list, but because you have set unique=true in items.xml, the list will have either 1 or 0 elements.

    SAP Commerce 123 Cloud Interactive Shortcut: If you are unable to create a new DAO interface yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/BandDAO.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/BandDAO.java

    ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/BandDAO.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/daos/BandDAO.java
    echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\daos\BandDAO.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\daos\BandDAO.java
  3. Create the DefaultBandDAO DAO implementation under the src/concerttours/daos/impl folder of the concerttours extension.
    package concerttours.daos.impl;
    import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
    import de.hybris.platform.servicelayer.search.FlexibleSearchService;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import concerttours.daos.BandDAO;
    import concerttours.model.BandModel;
     
    @Component(value = "bandDAO")
    public class DefaultBandDAO implements BandDAO
    {
        /**
        * Use SAP Commerce
                                    Cloud FlexibleSearchService for running queries against the database
         */
        @Autowired
        private FlexibleSearchService flexibleSearchService;
        /**
         * Finds all Bands by performing a FlexibleSearch using the {@link FlexibleSearchService}.
         */
        @Override
        public List<BandModel> findBands()
        {
            // Build a query for the flexible search.
            final String queryString = //
                    "SELECT {p:" + BandModel.PK + "} "//
                            + "FROM {" + BandModel._TYPECODE + " AS p} ";
            final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
            // Note that we could specify paginating logic by providing a start and count variable (commented out below)
            // This can provide a safeguard against returning very large amounts of data, or hogging the database when there are
            // for example millions of items being returned.
            // As we know that there are only a few persisted bands in this use case we do not need to provide this.
            //query.setStart(start);
            //query.setCount(count);
            // Return the list of BandModels.
            return flexibleSearchService.<BandModel> search(query).getResult();
        }
        /**
         * Finds all Bands by given code by performing a FlexibleSearch using the {@link FlexibleSearchService}.
         */
        @Override
        public List<BandModel> findBandsByCode(final String code)
        {
            final String queryString = //
                    "SELECT {p:" + BandModel.PK + "}" //
                            + "FROM {" + BandModel._TYPECODE + " AS p} "//
                            + "WHERE " + "{p:" + BandModel.CODE + "}=?code ";
            final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
            query.addQueryParameter("code", code);
            return flexibleSearchService.<BandModel> search(query).getResult();
        }
    }
    • The DAO uses SAP Commerce Cloud Flexible Search Query to construct its queries. The DefaultBandDAO class uses the SAP Commerce Cloud Flexible Search Query for the queries. If you want to persist new Band items in the DAO, use the save method of the model service. However, as shown in the diagram in the introduction, you can call the model service save method in the service class instead.
    • By separating the DAO logic into its own POJO, it is easier to test and clearer to develop.
    • At the top of the DefaultBandDAO class, there is an annotation that is provided by the Spring framework: @Component (value = "bandDAO"). This annotation tells Spring to define a bean, an instance of this class, called bandDAO that it can use for wiring dependencies. However, you need to tell Spring that it should scan this package to look for annotation-defined beans. To do so, add a context:component-scan tag to the application context.

    SAP Commerce 123 Cloud Interactive Shortcut: If you are unable to create the DAO implementation yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultBandDAO.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/impl/DefaultBandDAO.java

    ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/impl/DefaultBandDAO.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultBandDAO.java
    echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\daos\impl\DefaultBandDAO.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\daos\impl\DefaultBandDAO.java
  4. Create the BandService band service interface under the src/concerttours/service folder of the concerttours extension.
    package concerttours.service;
    import java.util.List;
    import concerttours.model.BandModel;
    
    public interface BandService
    {
       /**
        * Gets all bands in the system.
        *
        * @return all bands in the system
        */
       List<BandModel> getBands();
       /**
        * Gets the band for the given code.
        *
        * @throws de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException
        *            in case more then one band is found for the given code
        * @throws de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException
        *            in case no band for the given code can be found
        */
       BandModel getBandForCode(String code);
    }

    SAP Commerce 123 Cloud Interactive Shortcut: If you are unable to create the band service interface yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service/BandService.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/BandService.java

    cp $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/BandService.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/service/BandService.java
    copy /y %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\service\BandService.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\service\BandService.java
  5. Create the DefaultBandService band service implementation under the src/concerttours/service/impl folder of the concerttours extension.
    package concerttours.service.impl;
    import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException;
    import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Required;
    import concerttours.daos.BandDAO;
    import concerttours.model.BandModel;
    import concerttours.service.BandService;
     
    public class DefaultBandService implements BandService
    {
        private BandDAO bandDAO;
        /**
         * Gets all bands by delegating to {@link BandDAO#findBands()}.
         */
        @Override
        public List<BandModel> getBands()
        {
            return bandDAO.findBands();
        }
        /**
         * Gets all bands for given code by delegating to {@link BandDAO#findBandsByCode(String)} and then assuring
         * uniqueness of result.
         */
        @Override
        public BandModel getBandForCode(final String code) throws AmbiguousIdentifierException, UnknownIdentifierException
        {
            final List<BandModel> result = bandDAO.findBandsByCode(code);
            if (result.isEmpty())
            {
                throw new UnknownIdentifierException("Band with code '" + code + "' not found!");
            }
            else if (result.size() > 1)
            {
                throw new AmbiguousIdentifierException("Band code '" + code + "' is not unique, " + result.size() + " bands found!");
            }
            return result.get(0);
        }
        @Required
        public void setBandDAO(final BandDAO bandDAO)
        {
            this.bandDAO = bandDAO;
        }
    }

    SAP Commerce 123 Cloud Interactive Shortcut: If you are unable to create the band service implementation yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service/impl/DefaultBandService.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/impl/DefaultBandService.java

    cp $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/impl/DefaultBandService.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/service/impl/DefaultBandService.java
    copy /y %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\service\impl\DefaultBandService.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\service\impl\DefaultBandService.java
  6. Configure Spring to register the DAO and DefaultBandService as Spring beans in <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/resources/concerttours-spring.xml

    Replace the previously used <beans xmlns=...> declaration with:

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.1.xsd"
        >
        <context:component-scan base-package="concerttours"/>
    

    Add:

    <alias name = "defaultBandService" alias = "bandService" />
    <bean id = "defaultBandService" class = "concerttours.service.impl.DefaultBandService" >
    <property name = "bandDAO" ref = "bandDAO" />
    </bean>

    SAP Commerce 123 Cloud Interactive Shortcut: If you are unable to register the DAO and DefaultBandService yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/resources/concerttours-spring.xml with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/resources/concerttours-spring.xml

    cp $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/resources/concerttours-spring.xml $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/resources/concerttours-spring.xml
    copy /y %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\resources\concerttours-spring.xml %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\resources\concerttours-spring.xml
  7. Rebuild SAP Commerce Cloud with Ant.
    cd $HYBRIS_HOME_DIR/hybris/bin/platform; ant clean all
    cd %HYBRIS_HOME_DIR%\hybris\bin\platform & ant clean all
  8. Run the testServiceLayerClassesExist acceptance test again and confirm that it now passes.
    cd $HYBRIS_HOME_DIR/hybris123; mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testServiceLayerClassesExist test
    cd %HYBRIS_HOME_DIR%\hybris123 & mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testServiceLayerClassesExist test
  9. Commit the changes to your local Git repository.
    cd $HYBRIS_HOME_DIR/hybris; git add . ; git commit -m "Extend the ServiceLayer" 
    cd %HYBRIS_HOME_DIR%\hybris & git add . & git commit -m "Extend the ServiceLayer"