java - 在 JPA 中从集合中的枚举搜索时类型错误

标签 java jpa enums jpa-2.0 criteria

我的类Role有一个属性enumP,它是:

@Convert(converter = EnumPConverter.class)
@Enumerated(EnumType.STRING)
private EnumP enumP;

这是转换器:

@Converter(autoApply = false)
public class EnumPConverter implements AttributeConverter<EnumP, String> {

    @Override
    public String convertToDatabaseColumn(final EnumP attribute) {
        switch (attribute) {
        case X:
            return "X";
        case Y:
            return "Y";
        case Z:
            return "Z";
        default:
            throw new DbException("Type of enumeration is unknown at the time of conversion to a DB value.",
                    new IllegalArgumentException("Value received : " + attribute));
        }
    }


    @Override
    public EnumP convertToEntityAttribute(final String dbData) {
        switch (dbData) {
        case "X":
            return EnumP.X;
        case "Y":
            return EnumP.Y;
        case "Z":
            return EnumP.Z;
        default:
            throw new DbException("Unknown enumerated value was found in the DB",
                    new IllegalArgumentException("Value received : " + dbData));
        }
    }
}

这是枚举:

public enum EnumP {
    X, Y, Z;
}

当谓词是:

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

其中getFilterSetValues()将返回一个字符串数组,如下所示:

["X", "Y"]

我收到以下异常:

Parameter value [X] did not match expected type [EnumP (n/a)]

我尝试在转换器上添加行断点,但调试器不会在那一行停止。

PS:我无权在 Enum 中进行修改,因此任何操作都应在转换器内完成。

最佳答案

如果具有相同的值 X->X、Y->Y、Z->Z ,为什么要使用转换器? 我认为 @Enumerated(EnumType.STRING) 足以满足您的情况,无需转换它们。

我同意@crizzis的观点,使用枚举的字符串值是一种不好的做法。更好的方法是实现 getFilterSetValues 以返回枚举值数组

关于java - 在 JPA 中从集合中的枚举搜索时类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403236/

相关文章:

java - 检查温度条件

java - 没有通过ajax从servlet获取html响应

google-app-engine - JPA 与 App Engine 上的低级数据存储

java - JPA EclipseLink 和动态 Jar 文件

swift - 无法访问公共(public)枚举 Swift 4.2

linq - 在 .NET 3.5 中的枚举列表上使用 List.Find 或 LINQ

java - 类 FileReader 中的构造函数 FileReader 不能应用于给定类型;

java - 如何在 Java 中比较字符串?

java - jpa条件查询获取列表中的重复值

spring - Spring 框架中的Jackson反序列化错误处理