java HQL 中的常量枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25114294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:22:12  来源:igfitidea点击:

constant enum value in HQL

javahibernateenumshql

提问by joro

I have got a working query, which I need to modify by filtering with constant enum value.

我有一个工作查询,我需要通过使用常量枚举值过滤来修改它。

Now it looks this way:

现在它看起来像这样:

public static final String venueQuery = 
       "select distinct v from package.Venue v "
        + "<some joins here> "
        + "WHERE v.venueType = package.enums.VenueType.VOUCHER_PROVIDER ";

Changing data this way causes

以这种方式更改数据会导致

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token

Column definition is like this:

列定义是这样的:

@Enumerated(EnumType.STRING)
@Column(name = "venue_type")
private VenueType venueType;

Enum definition looks this way:

枚举定义是这样的:

public enum VenueType {
    RESTAURANT, BAR, CAFE, FUN_CLUB, VOUCHER_PROVIDER
}

I am sure that other parts of query works fine, because after removing it, no exceptions are thrown.

我确信查询的其他部分工作正常,因为在删除它之后,不会抛出任何异常。

Are there tricks for setting constant enum value in HQL query?

在 HQL 查询中是否有设置常量枚举值的技巧?

回答by icza

The preferred way would be to go about adding parameters to the query and pass the enum instance as the parameter value, but if you don't (or can't) make it a parameterized query, you can still do it with Stringconcatenation like this:

首选的方法是向查询添加参数并将枚举实例作为参数值传递,但是如果您不(或不能)使其成为参数化查询,您仍然可以通过这样的String连接来完成:

public static final String venueQuery = 
   "select distinct v from package.Venue v "
    + "<some joins here> "
    + "WHERE v.venueType = '" + VenueType.VOUCHER_PROVIDER.name() +"'";

If you want it a compile time constant query String:

如果你想要一个编译时常量查询String

public static final String venueQuery = 
   "select distinct v from package.Venue v "
    + "<some joins here> "
    + "WHERE v.venueType = 'VOUCHER_PROVIDER'";