springspring-bootjpaspring-data-jpah2

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


Solution

  • 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.