我的类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/