Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 918
Maifee Ul Asad Avatar asked Jan 25 '23 11:01

Maifee Ul Asad


2 Answers

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.

like image 65
Robert Niestroj Avatar answered Jan 28 '23 00:01

Robert Niestroj


Your database contains an entry with role = 2.

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

like image 27
Simon Martinelli Avatar answered Jan 28 '23 00:01

Simon Martinelli