views:

380

answers:

2

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 ?

+1  A: 

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.

skaffman
skaffman: thanks for your quick answer. I just briefed the Projections part, and found that PropProjection.Property.forName("name") could be used to filter a subset of columns as the result, But i couldn't find a Projection that maps two Persistance classes into a new class, like the Family class in the above example ? Could you shed some light on that ?
Visus Zhao
+2  A: 

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);  
Pascal Thivent
Thanks so much! That's exactly what i was looking for!Seems Criteria is almost as powerful as HQL.Thanks!
Visus Zhao