Maifee Ul Asad
Maifee Ul Asad

Reputation: 4627

InvalidDataAccessApiUsageException: No enum constant

I have a Role enum, like this:

public enum Role{
    admin('a'),
    member('m'),
    pending('p');
    char role;
    Role(char a) {
        this.role = a;
    }
    public char getRole() {
        return role;
    }
    public static Role getByRole(char role) {
        return Arrays.stream(Role.values())
                .filter(Role -> Role.getRole() == role)
                .findFirst()
                .orElse(Role.pending);
    }
}

To support conversion, I have created a class called RoleConverter:

@Converter
public class RoleConverter implements AttributeConverter<Role, Character> {
    @Override
    public Character convertToDatabaseColumn(Role Role) {
        return Role.getRole();
    }
    @Override
    public Role convertToEntityAttribute(Character dbData) {
        System.out.println(dbData);
        return Role.getByRole(dbData);
    }
}

And in my Target object I have added proper annotations:

    @Convert(converter = RoleConverter.class)
    @Enumerated(EnumType.STRING)
    public Role role;

Still it gives me error - nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: No enum constant com.mua.cse616.model.Role.2;

Using spring with h2 and jpa

Upvotes: 6

Views: 14839

Answers (3)

Michael Schreiber
Michael Schreiber

Reputation: 43

Old question but people - as I - still find it. My understanding is that @Enumerated and @Convert cannot be used together.

@Convert(converter = RoleConverter.class)
@Enumerated(EnumType.STRING)

Upvotes: 0

Robert Niestroj
Robert Niestroj

Reputation: 16141

Seems like you have a row in your DB which has in the column the value 2 which obviously is not present in the enum. Maybe you started out without the @Enumerated annotation thus JPA used the ordinal as the column value.

Upvotes: 15

Simon Martinelli
Simon Martinelli

Reputation: 36213

Your database contains an entry with role = 2.

Make sure that the entries in the database have the same values as in your Enum.

Upvotes: 2

Related Questions