Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I refer to inner enums (defined within an entity) from a JPQL query using Hibernate?

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'
like image 472
Gabriel Bauman Avatar asked Mar 14 '16 18:03

Gabriel Bauman


People also ask

Can I use JPQL with Hibernate?

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.

How does Hibernate store enums?

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.

What annotation is used if enum is used in an entity?

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.

Which is true about JPQL Hql?

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.


1 Answers

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.

like image 106
Gabriel Bauman Avatar answered Sep 18 '22 18:09

Gabriel Bauman