简体   繁体   English

如何访问HQL中的枚举属性?

[英]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 to 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? 除了将Priority作为实体创建之外,还有其他想法吗?

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. HQL查询将转换为SQL以便执行,因此HQL查询中引用的所有属性都应存储在数据库中。 Since your index property is not stored in the database, HQL query with it can't be converted to SQL query. 由于您的index属性未存储在数据库中,因此带有它的HQL查询无法转换为SQL查询。

You can use enums in ORDER BY clause of HQL query only to sort by the natural order of their database representation (ie names or ordinal numbers). 您只能在HQL查询的ORDER BY子句中使用枚举,以按其数据库表示的自然顺序(即名称或序数)进行排序。

You have several options: 您有几种选择:

  1. Organize your enum s so that order of their declarations matches the desired order of their index es and configure Hibernate to store them in the database as ordinal numbers. 组织您的enum使它们的声明顺序与所需的index顺序匹配,并配置Hibernate将它们存储为序号。 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. 使用@Embeddable / <component>类而不是enumindex存储在数据库中。

  3. Write a custom type to represent your enum as index . 编写一个自定义类型以将您的枚举表示为index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM