Blazebit / blaze-persistence

Rich Criteria API for JPA providers
https://persistence.blazebit.com
Apache License 2.0
727 stars 85 forks source link

Allow BlazeCriteriaQuery to apply to a BaseCriteriaBuilder #1557

Open beikov opened 2 years ago

beikov commented 2 years ago

As shown in the user question it is hard to compose JPA Criteria parts into a bigger query. My suggestion is to add the following to BlazeCriteriaQuery:

    public void applyToCriteriaBuilder(BaseCriteriaBuilder<T> builder);

This will allow users to compose a query like this:

CriteriaBuilder<Tuple> cb1 = factory.create(em, Tuple.class);
query1.applyToCriteriaBuilder( cb1 );
LeafOngoingSetOperationCriteriaBuilder<Tuple> cb2 = cb.unionAll();
query2.applyToCriteriaBuilder( cb2 );
FinalSetOperationCriteriaBuilder<Tuple> finalCb = cb2.endSet();
finalCb.orderByDesc("statusChangedAt").orderByDesc("id")

To fully solve the problem for the user we'd also need https://github.com/Blazebit/blaze-persistence/issues/1556 though.

donalpmccarthy commented 1 year ago

It would be super helpful if this apply functionality was available more generically. I have a requirement to support a filter on an analytic function - but these window functions aren’t supported in the where clause. The work around is either a select from a CTE or a sub query. It would be helpful if you already have a criteria query to be able to pass it into a fromWith or fromSubquery. So we end up with either:

select * from (…) a where a.rank = 1

or

with a as (…) select * from a where a.rank =1

In this example rank is a window function in the CTE or sub query of the form “rank() over (partition by … order by …) as rank”

When you already have a JPA criteria query but simply wish to wrap it in a parent select like above, I cannot see an easy way to achieve this without rebuilding the whole query from scratch using the BlazeCriteriaBuilder. Any help appreciated on this request!

thanks - d