Is there any example how to load data from datasource into service?

What am i going for:

i need to write a service which is looping trough records in specific entity based on some conditions.
service will then generate document and create related record.

i´d like to run that service/bean periodically via buildin scheduled tasks.

I am new to cuba and cant find some similiar example.

Without knowing the specifics, I would pass in to the service’s method the parameters needed to load the data and then use DataManager.load()… to load said data.

So if say it was a service to do something to customers of a specific type, I would have a method in the service called doSomethingToCustomersOfType(CustomerType type) and in that method set up a query to load those customers and then iterate over them.

public void doSomethingToCustomersOfType(CustomerType type) {
    List<Customer> customers = dataManager.load(Customer.class)
        .query("select c from app_Customer c where c.type = :type")
        .parameter("type", type)
        .list();

    // do stuff!
}

I was trying something like this, but getting nullPointException:

package com.company.ramcovezmluvy.service;

import com.company.ramcovezmluvy.entity.NavrhyPlatby;
import com.haulmont.cuba.core.global.DataManager;

import javax.inject.Inject;
import java.util.List;

public interface GenerateProformaService {
    String NAME = "ramcovezmluvy_GenerateProformaService";

    class Proforma {
        @Inject
        DataManager dataManager;

        private List<NavrhyPlatby> getNavrhyPlatby() {
            try {
                return dataManager.load(NavrhyPlatby.class)
                        .query("select e from NavrhyPlatby e")
                        .view("navrhyPlatby-browser-view")
                        .list();
            } catch(NullPointerException e){
                e.printStackTrace();
                return null;
            }
        }


        public static void main(String[] args) {
            Proforma p = new Proforma();
            List inti = p.getNavrhyPlatby();
            System.out.println("Záznam logu:" + inti.size());

            assert inti.size() != 0;
        }
    }
}

Thank you Jon. Finally figured it out. But than i figured out i need to move it to bean so i can trigger it by scheduled task interface. Also modved to using entitymanager rather than datamanager. Your answer helped me lot.

1 Like