Hibernate Criteria API equivalent to HQL select clause?

可紊 提交于 2020-01-02 05:08:06

问题


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.



来源:https://stackoverflow.com/questions/2801764/hibernate-criteria-api-equivalent-to-hql-select-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!