I'd like to have a combined query for two persistent classes.
In HQL this could be achieved by the select clause,
select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
In the above example, Family is a conbined class with DemesticCat as its construtor params
What is the Criteria equivalent of the HQL select clause ?
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.
Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.
HQL From: HQL From is same as select clause in SQL, from Employee is same as select * from Employee . We can also create alias such as from Employee emp or from Employee as emp . HQL Join : HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a.
The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.
You'll have to use a ResultTransformer
for this. The Hibernate 3.2: Transformers for HQL and SQL blog post gives the following example (where StudentDTO
is a non-entity Bean):
List resultWithAliasedBean = s.createCriteria(Enrolment.class)
.createAlias("student", "st").createAlias("course", "co")
.setProjection( Projections.projectionList()
.add( Projections.property("st.name"), "studentName" )
.add( Projections.property("co.description"), "courseDescription" )
)
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class) )
.list();
StudentDTO dto = (StudentDTO)resultWithAliasedBean.get(0);
In the Criteria API, this functionality is handled by Projections. The documentation is a bit confusing and over-complicated, but that's what you need to look at.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With