Spring JpaRepository ENUM mismatch

john :

My enum class is as follows:

public enum Sex {

    MALE('M'), FEMALE('F'), UNKNOWN('U');

    char name;

    Sex(char name) {
        this.name = name;
    }

    public char getName() {
        return name;
    }
}

My H2 database schema for the attribute is as follows:

sex CHAR(1),

My model class is:

@Column
@NotNull
@Enumerated(EnumType.STRING)
private Sex sex;

When I try to populate my models via JpaRepository I get an exception as follows: java.lang.IllegalArgumentException: No enum constant com.awesome.enumeration.Sex.M

What is preventing me from mapping my DB to the enum?

michalk :

You could write a custom converter for your enum :

@Converter
public class SexConverter implements AttributeConverter<Sex, Character> {


    @Override
    public Character convertToDatabaseColumn(Sex sex) {
        return sex.getName();
    }

    @Override
    public Sex convertToEntityAttribute(Character dbData) {
        return Sex.getByName(dbData);
    }
}

Then in your entity :

@Entity
public class TestEntity {

    @Column
    @NotNull
    @Convert(converter = SexConverter.class)
    private Sex sex;
}

I also created helper static method on your enum to get enum by char name :

public enum Sex {

    MALE('M'), FEMALE('F'), UNKNOWN('U');

    char name;

    Sex(char name) {
        this.name = name;
    }

    public char getName() {
        return name;
    }

    public static Sex getByName(char name) {
        return Arrays.stream(Sex.values())
                .filter(sex -> sex.getName() == name)
                .findFirst()
                .orElse(UNKNOWN);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80674&siteId=1