Calculation of attribute value from aggregation of two associated entity (not composition)

I have three entities -
First entity is HZW with name and inventory attribute.

Second entity HZdisposal have n-1 association with HZW and attribute date, HZW, disposedQuantity.

Third entity HZgeneration have n-1 association with HZW and attribute date, HZW, generatedQuantity.

What is the best method to recalculate HZW,inventory whenever there are addition, deletion or edit in HZdisposal and HZgeneration entities.

Thanks

I tried it by using postcommit in both HZgenerationEdit and HZdisposalEdit and using nativequery in service bean.

@Subscribe(target = Target.DATA_CONTEXT)
private void onPostCommit(DataContext.PostCommitEvent event) {
    HazardousWasteService.updateInventory(getEditedEntity().getHazardousWaste());
}

but it is giving exception - NullPointerException on this line
HazardousWasteService.updateInventory(getEditedEntity().getHazardousWaste());

The service bean interface is

package com.company.sheeloffice.service;

import com.company.sheeloffice.entity.HazardousWaste;

public interface HazardousWasteService {
    String NAME = "sheeloffice_HazardousWasteService";
    void updateInventory(HazardousWaste HazardousWaste);
}

Bean usesw nativequery for calculating total generation and total disposal for particular HazardousWaste (HZW) and calculate inventory and save it the database using nativequery again.

thanks in advance

Please delete my reply as it was due to variable name.

I am able to get the desired results by nativesql but is there a better method using cuba framework?

Secondly in below code used

    Query query = em.createNativeQuery(
                        "select sum(o.Quantity) from SHEELOFFICE_HAZARDOUS_WASTE_GENERATION o where o.HAZARDOUS_WASTE_ID = #login");
                query.setParameter("login", MyParameter);
                tg = (double) query.getSingleResult() ;

this line " tg = (double) query.getSingleResult() " gives exception if there is no data in database. How I can solve this issue.
PS: I am new to java and cuba

Thanks

This code solved the issue

tg = (query.getSingleResult()==null) ? 0:(double) query.getSingleResult();

I am able to get the desired results by nativesql but is there a better method using cuba framework?

Thanks and regards

You can use DataManager and JPQL:

BigDecimal sum = dataManager.loadValue(
        "select sum(o.amount) from demo$Order o " +
        "where o.date >= :date group by o.customer", BigDecimal.class)
    .parameter("date", orderDate)
    .one();