如何访问 HQL 中的枚举属性?
我有一个像这样的枚举:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能这样做。
HQL查询会转换为SQL来执行,因此HQL查询中引用的所有属性都应该存储在数据库中。由于您的
index
属性未存储在数据库中,因此使用它的 HQL 查询无法转换为 SQL 查询。您可以在 HQL 查询的 ORDER BY 子句中使用枚举,仅按其数据库表示的自然顺序(即名称或序数)进行排序。
您有多种选择:
组织您的
enum
,使其声明的顺序与其索引
所需的顺序相匹配,并配置 Hibernate 将它们存储在数据库中:序数。如果已经配置,在您的情况下,所需的查询将是Use
@Embeddable
/
class 而不是enum
来将index
存储在数据库中。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:
Organize your
enum
s so that order of their declarations matches the desired order of theirindex
es and configure Hibernate to store them in the database as ordinal numbers. If it's already configured, in your case the desired query would beUse
@Embeddable
/<component>
class instead ofenum
to storeindex
in the database.index
.