I'm trying to create a query using CriteriaBuilder to select all Product with a stock greater than zero. Stock is sum(DeliveryRow.amount) - sum(DispatchRow.amount). Both ofcourse only containing the right Product.
I have tried creating Subquery for both DeliveryRow and DispatchRow though I feel like this should be done using a join().
Classes
Product { 
    (...)
}
DeliveryRow {
    @ManyToOne
    private Product product;
    private int amount;
}
DispatchRow {
    @ManyToOne
    private Product product;
    private int amount;
}
Query
In this query I'm not sure how to handle the xxx. I've tried making to subqueries but that didn't work out.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root product = query.from(Product.class);
query.select(product);
// sum of DeliveryRow.amount where DeliveryRow.product = Product
// minus 
// sum of DispatchRow.amount where DispatchRow.product = Product
Expression stock = xxx;  
query.where(cb.gt(stock, Integer.parseInt(0)));
return em.createQuery(query).getResultList();
Any suggestions on how to solve this?