Hibernate Criteria API equivalent to HQL select cl

2019-05-02 11:22发布

问题:

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:

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


回答2:

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.