I'm trying to prevent having to create one separate query for count and one for the actual query. What I found is SesssionImpl::createQuery takes a considerable amount of time for a complex query and by combining count and the main query I can then eliminate one createQuery call.
In SQL I can do something like
select count(*) over(), col_A, col_B
from TABLE_XX
where col_C > 1000
Can this be achieved in hibernate?
(I'm trying to avoid native sql and stick to HQL and detached criteria. Using native SQL defeats the purpose of using hibernate. My system has to support both Oracle and Sybase)
You can use this for :-
Hibernate's
@Formula
annotation may work as a workaround. Provide an additional column in your@Entity
to represent the count, annotated with@Formula
which contains theCOUNT OVER
query:With this approach, Hibernate butchers the generated SQL a bit, though, so you may also need to register an
Interceptor
to clean up the SQL:Aside from the explicit Hibernate dependencies (rather than pure JPA), there is one other downside, such that this column will be loaded by default which may add some unnecessary overhead to queries where the count is not needed. It may be possible to make the column optional and lazily loaded, but this requires bytecode instrumentation and adds further layers of complexity.