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

发布于 2024-10-15 17:27:21 字数 527 浏览 2 评论 0原文

我有一个像这样的枚举:

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;
}
}

...并且我有一个具有优先级的票证实体。问题:我需要按优先级对结果进行排序,所以我认为这会起作用,但事实并非如此:

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

我从 Hibernate 收到错误。除了创建 Priority 作为一个实体之外,还有什么想法吗?

感谢您的任何建议! :)

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?

Thanks for any suggestion! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深白境迁sunset 2024-10-22 17:27:21

你不能这样做。

HQL查询会转换为SQL来执行,因此HQL查询中引用的所有属性都应该存储在数据库中。由于您的 index 属性未存储在数据库中,因此使用它的 HQL 查询无法转换为 SQL 查询。

您可以在 HQL 查询的 ORDER BY 子句中使用枚举,仅按其数据库表示的自然顺序(即名称或序数)进行排序。

您有多种选择:

  1. 组织您的enum,使其声明的顺序与其索引所需的顺序相匹配,并配置 Hibernate 将它们存储在数据库中:序数。如果已经配置,在您的情况下,所需的查询将是

    从 Ticket t order by t.priority desc 中选择 t
    
  2. Use @Embeddable/ class 而不是 enum 来将 index 存储在数据库中。

  3. 编写一个自定义类型来将您的枚举表示为 index

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文