Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

Wrong type when searching from enum in collection in JPA

My class Role has a property enumP which is :

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

This is the converter :

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

And this is the Enum :

public enum EnumP {
    X, Y, Z;
}

When the predicate is:

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

Where getFilterSetValues() will return a String array as following:

["X", "Y"]

I get the following exception :

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

I tried to add a line breakpoint on the converter but the debugger doesn't stop in that line.

PS : I have no right to modify in the Enum so any manipulation should be done inside the converter.

Upvotes: 0

Views: 882

Answers (2)

Fran&#231;ois LEPORCQ
Fran&#231;ois LEPORCQ

Reputation: 552

Why use a converter if you have the same values X->X, Y->Y, Z->Z ? I think @Enumerated(EnumType.STRING) is suffisant in your case, no need to convert them.

i'm agree with @crizzis it's a bad practice to use string value of an enum. the better is to implement your getFilterSetValues to return an array of enump values

Upvotes: 1

crizzis
crizzis

Reputation: 10716

Since Role.enumP is of type EnumP while getFilterSetValues() returns an array of strings, there is an obvious type mismatch. You need to pass an array of EnumP to the in() method instead.

Upvotes: 0

Related Questions