joro joro - 1 month ago 12
Java Question

constant enum value in HQL

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?

Answer

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 String concatenation like this:

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:

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