Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use constant (EnumType Ordinal) value in @Query annotation in JPA repository?

Enum,

public enum CountEnum {
   ONE,
   TWO
}

Entity class,

@Entity
public class Test {
...
    @Enumerated(EnumType.ORDINAL)
    private CountEnum countEnum;
...
}

I want to query all the Test rows having countEnum 'ONE'. But as here @Enumerated(EnumType.ORDINAL) is ordinal, I have to put int value of 'ONE' in @Query instead of String.

My Repository Interface,

public interface ResourceRepository extends JpaRepository<Test, String> {
    @Query(" select test from Test test where test.countEnum = " + CountEnum.ONE.ordinal())
    List<Test> find();
}

But it throws an error saying Attribute value must be constant. So how do I will query all those rows using ordinal value of enum as I don't want to put hardcoded constant values?

like image 427
Chinmoy Acharjee Avatar asked Mar 04 '23 00:03

Chinmoy Acharjee


1 Answers

Why do you think you have to use the ordinal value when writing JPQL?

The JPA Specification says:

4.6.1 Literals

[...] Enum literals support the use of Java enum literal syntax. The fully qualified enum class name must be specified.

I therefore would expect something like the following to work:

public interface ResourceRepository extends JpaRepository<Test, String> {
    @Query(" select test from Test test where test.countEnum = com.somepackage.with.sub.pakcages.CountEnum.ONE")
    List<Test> find();
}
like image 109
Jens Schauder Avatar answered Apr 07 '23 14:04

Jens Schauder