简体   繁体   English

带有枚举的JPA 2 Criteria API

[英]JPA 2 Criteria API with enums

I have the following entity : 我有以下实体:

public class Role extends AbstractDomain<Long> {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen_x")
    @UiInfo(name = "Identifiant")
    private Long roleId;

    @Column
    @UiInfo(name = "Libellé")
    private String lib;

    @Column
    @UiInfo(name = "Provenance")
    private EnumP enumPID;
}

EnumP : 枚举:

public enum EnumP {
    W, X, Y, Z;
}

And using JPA Criteria API I want to get a list of Role where Role.enumPID in an array contains the enum values as strings. 使用JPA Criteria API,我想获得一个Role列表,其中数组中的Role.enumPID包含枚举值作为字符串。

This is the code of the Predicate I tried : 这是我尝试过的Predicate的代码:

builder.isTrue(fromRole.get(Role_.enumPID).in((Object[]) filter.getFilterSetValues()))

And the filter.getFilterSetValues() contains the enum values as strings, as following : 并且filter.getFilterSetValues()包含枚举值作为字符串,如下所示:

["X","Y"]

But I get this error message : 但我收到此错误消息:

java.lang.IllegalArgumentException: Parameter value [X] did not match expected type [***.EnumP (n/a)]

How can I solve this ? 我该如何解决?

You should adequately annotate the enum field first: 您应该首先对枚举字段进行充分注释:

@Enumerated(EnumType.STRING)
@UiInfo(name = "Provenance")
private EnumP enumPID;

Then you should be using the particular EnumP elements in your queries as params, not their String equivalents. 然后,您应该在查询中使用特定的EnumP元素作为参数,而不是它们的String等效项。

You would need to transform the collection of Strings into corresponding collection of EnumP objects: 您需要将字符串的集合转换为相应的EnumP对象的集合:

public static List<EnumP> fromStringArray(String[] array){
    List<EnumP> returnList = new ArrayList<>; 

    for(String element: array){
       for(EnumP enumP: EnumP.values()){
          if(enumP.name().equals(element)){
             returnList.add(enumP);
          }
       }
    }    

    return returnList;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM