有什么方法可以在JPA信息库的@Query注释中使用常量(EnumType Ordinal)值?

时间:2019-05-14 12:42:31

标签: java hibernate spring-boot jpa spring-data-jpa

枚举

public enum CountEnum {
   ONE,
   TWO
}

实体类

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

我想查询所有具有countEnum Test的{​​{1}}行。但是由于这里'ONE'是序数,因此我必须将@Enumerated(EnumType.ORDINAL)的int值放在'ONE'中而不是String中。

我的存储库界面,

@Query

但是它抛出一个错误,提示public interface ResourceRepository extends JpaRepository<Test, String> { @Query(" select test from Test test where test.countEnum = " + CountEnum.ONE.ordinal()) List<Test> find(); } 。那么,由于我不想放置硬编码的常量值,我将如何使用枚举的序数查询所有这些行?

4 个答案:

答案 0 :(得分:2)

为什么您认为编写JPQL时必须使用序数值?

JPA规范说:

  

4.6.1文字

     

[...]   枚举文字支持Java枚举文字语法的使用。必须指定标准的枚举类名称。

因此,我希望可以进行以下操作:

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();
}

答案 1 :(得分:1)

使用常规方法,例如:

public interface ResourceRepository extends JpaRepository<Test, String> {

    List<Test> findByCountEnum(CountEnum ce);
}

答案 2 :(得分:1)

将查询定义为字符串常量:

private static final String QUERY_FIND = " select test from Test test where test.countEnum = " + CountEnum.ONE.ordinal();

然后在注释中使用常量:

public interface ResourceRepository extends JpaRepository<Test, String> {
    @Query(QUERY_FIND)
    List<Test> find();
}

答案 3 :(得分:1)

如果您为枚举分配常量值:

public enum CountEnum {
    ONE(Constants.ONE_VALUE), TWO(Constants.TWO_VALUE);

    CountEnum(int countEnum) {
    }

    public static class Constants  {
        public static final int ONE_VALUE = 0;
        public static final int TWO_VALUE = 1;
    }
}

然后,您可以在@Query注释中使用枚举:

public interface ResourceRepository extends JpaRepository<Test, String> {
    @Query(" select test from Test test where test.countEnum = " + CountEnum.Constants.ONE_VALUE)
    List<Test> find();
}
相关问题