Hibernate Criteria API equivalent to HQL select cl

2019-05-02 10:56发布

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 ?

2条回答
地球回转人心会变
2楼-- · 2019-05-02 11:02

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.

查看更多
在下西门庆
3楼-- · 2019-05-02 11:12

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);  
查看更多
登录 后发表回答