1

I'm using reactive MongoDB in spring. Here is the Enum Language:

public enum Language {
    ARABIC("ar"),
    UZBEK("uz");

    private final String code;

    Language(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static Language getLanguage(String codeString) {
        return Stream.of(Language.values())
                .filter(code -> codeString.equals(code.getCode()))
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
    }
}

Here are the converters:

@ReadingConverter
public class EnumReadingConverter implements Converter<String, Language> {

    @Override
    public Language convert(String source) {
        return Language.getLanguage(source);
    }
}

@WritingConverter
public class EnumWritingConverter implements Converter<Language, String> {
    @Override
    public String convert(Language source) {
        return source.getCode();
    }
}

Problem: When I write to the database it is writing Language enum as "ARABIC" or "UZBEK" anyway. It should write as "uz" or "ar". Why is not saving like this?

4

1 回答 1

1

一切都是正确的,除了我忘记注册这样的转换器:

@Configuration
public class MongoDBConfiguration {

    @Bean
    public MongoCustomConversions customConversions(){
        List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
        converterList.add(new EnumReadingConverter());
        converterList.add(new EnumWritingConverter());
        return new MongoCustomConversions(converterList);
    }
}

感谢Smutje的建议!

于 2020-11-19T15:17:51.057 回答