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
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.
Your database contains an entry with role = 2.
Make sure that the entries in the database have the same values as in your Enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With