tags:

views:

89

answers:

1
+2  Q: 

Criteria to HQL

Hi,

is there any way to take a Criteria (that has multiple Criterias, Restrictions and Orders) and generate a HQL query out of it?

Cheers

Nik

+1  A: 

Sadly, Criteria API is not thought out very well.

While the fact that it won't generate HQL for you is understandable (Criteria is provided as an alternative to HQL after all), there is no way to do it yourself either - not without patching Hibernate code. Criteria class is a one-way street; it maintains all the conditions / associations / etc... you've supplied to it but doesn't provide a way for you to get them back.

Take a look at Hibernate Generic DAO framework, particularly at its Search component (which you can use standalone). That's what Criteria API should have been :-) and it would generate either Hibernate- or JPA-compliant QL query for you (along with many other nice features)

ChssPly76
Yup, hope someone has a large patch going for Hibernate 3.5 or 4 ;-)
niklassaers
Well, if you **really** need to use Criteria, it's not that hard to patch. You basically need to introduce a bunch of public methods to `CriteriaImpl` and (depending on what you need) `Criterion` and its implementations. The obvious problem with this approach, of course, is that you get to redo it on each upgrade :-)
ChssPly76