I have an entity class as follows:
package stuff;
@Entity
class Thing {
@Id
@GeneratedValue
private Long id;
@Basic
@Enumerated
private State state;
public enum State {
AWESOME,
LAME
}
}
How can I select all Things with state AWESOME using JPQL and Hibernate?
select t from Thing t where t.state=stuff.Thing.State.AWESOME
...gives the error...
org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'stuff.Thing.State.AWESOME'
Hibernate, or any other JPA implementation, has to transform the JPQL query into SQL. It is, therefore, a good practice to activate the logging of the SQL statements during development to check the generated SQL statements.
By default, Hibernate maps an enum to a number. It uses the ordinal value, which is the zero-based position of a value within the definition of the enum. So, the enum value that's defined first gets mapped to 0, the second one to 1 and so on.
The most common option to map an enum value to and from its database representation in JPA before 2.1 is to use the @Enumerated annotation.
The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.
Use the following idiom:
select t from Thing t where t.state=stuff.Thing$State.AWESOME
Type$InnerType
is Java's naming convention for inner types.
When you try to use dot notation, Hibernate assumes that you're trying to access nested properties, which (properly) fails in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With