Search code examples
javaodataolingo

How to implement pagination with Apache Olingo V2?


I need to use Apache Olingo V2 to implement an API using pagination. This means that I need to provide a simple URL for a collection of entities supporting basic $top and $skip operators, just like in the example below:

https://services.odata.org/OData/OData.svc/Products?$top=5&$skip=3

I am not using the Annotation Processor extension or the JPA Processor Extension, so they are not an option for implementing this pagination.

I checked the Olingo V2 Server documentation but could not find an example for implementing pagination.


Solution

  • If you are not using the Annotation Processor extension or JPA Processor extension you would have implemented/extended ODataSingleProcessor. You can retrieve the $skip and $top value from the URL from GetEntitySetUriInfo type argument and utilize to fetch data accordingly.

    Below is the sample code for the same, you might want to do null checks and other sensitization.

    @Override
    public ODataResponse readEntitySet(GetEntitySetUriInfo uriInfo, String contentType) throws ODataException {
    
            int skipValue = uriInfo.getSkip();
            int topValue = uriInfo.getTop();
    
            URI serviceRoot = getContext().getPathInfo().getServiceRoot();
            ODataEntityProviderPropertiesBuilder propertiesBuilder = EntityProviderWriteProperties
                    .serviceRoot(serviceRoot);
    
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    
            // fetch data from the datasource considering the skip and top values 
            // one example could be SELECT * FROM table LIMIT topValue OFFSET skipValue
            // fill in the data variable
    
            return EntityProvider.writeFeed(contentType, uriInfo.getStartEntitySet(), data, propertiesBuilder.build());
    
        }