开发者

How can I access enum atributes in HQL?

I have an Enum like this:

TicketPriority {

LOW(4),
NORMAL(3),
HIGH(2),
IMMEDIATE(1);

private Integer index;

TicketPriority (Integer index){
    this.index = index;
}

public Integer getIndex(){
    return this.index;
}

public void setIndex(Integer index){
    this.index = index;
}
}

... and I have an Ticket entity that has a priority. The problem: I need t开发者_StackOverflow中文版o order my results by priority so I thought that this would work, but it didn't:

select t from Ticket t order by t.priority.index

I got an error from Hibernate. Any idea besides create Priority as an entity?

Thanks for any suggestion! :)


You cannot do it this way.

HQL query is converted to SQL for execution, therefore all properties referenced in HQL query should be stored in the database. Since your index property is not stored in the database, HQL query with it can't be converted to SQL query.

You can use enums in ORDER BY clause of HQL query only to sort by the natural order of their database representation (i.e. names or ordinal numbers).

You have several options:

  1. Organize your enums so that order of their declarations matches the desired order of their indexes and configure Hibernate to store them in the database as ordinal numbers. If it's already configured, in your case the desired query would be

    select t from Ticket t order by t.priority desc
    
  2. Use @Embeddable/<component> class instead of enum to store index in the database.

  3. Write a custom type to represent your enum as index.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜