Visus Zhao
Visus Zhao

Reputation: 1154

Hibernate Criteria API equivalent to HQL select clause?

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 ?

Upvotes: 5

Views: 2514

Answers (2)

Pascal Thivent
Pascal Thivent

Reputation: 570325

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);  

Upvotes: 5

skaffman
skaffman

Reputation: 403461

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.

Upvotes: 1

Related Questions