如何在HQL查询中按列表排序?

时间:2010-06-07 10:54:53

标签: java hibernate orm

这是我的情况:
我有两个实体,其中一对多关系映射为(仅给出相关部分):

    <class name="xyz.Survey">
        <list name="answers" inverse="true" lazy="true" fetch="select" 
cascade="all-delete-orphan">
            <key column="OPA_OP_ID" not-null="true" />
            <list-index column="OPA_SORT_ORDER" />
            <one-to-many class="xyz.Answer" />
        </list>
    </class>
    <class name="xyz.Answer">
        <many-to-one name="survey" class="xyz.Survey" fetch="select">
            <column name="OPA_OP_ID" not-null="true" />
        </many-to-one>
there is no mapping for column OPA_SORT_ORDER, I let Hibernate take care of that
    </class>

我的问题是:我想对单个调查的答案执行HQL查询,我希望这些答案按OPA_SORT_ORDER排序。此查询不起作用:

select new AnswerDTO(a.id, a.answerText, 0) 
from Survey p 
join p.answers a
where p.id = ? 

在日志中,我可以看到此HQL生成的SQL查询中没有ORDER BY。我怎样才能做到这一点?我是否需要将sortOrder属性添加到Answer实体?

1 个答案:

答案 0 :(得分:5)

不,你不需要添加属性,HQL有一个内置函数index

select new AnswerDTO(a.id, a.answerText, 0) 
from Survey p 
join p.answers a
where p.id = ? 
order by index(a)