Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data mongodb enum mapping converter

I would like code not throws exception when java code load enum value from mongo that not exists in enum code

Exemple :

java.lang.IllegalArgumentException: No enum constant fr.myapp.type.OrderOptionEnum.TELEPHONE
at java.lang.Enum.valueOf(Enum.java:238)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getPotentiallyConvertedSimpleRead(MappingMongoConverter.java:819)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readCollectionOrArray(MappingMongoConverter.java:909)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1184)

Because TELEPHONE not existe in OrderOptionEnum

I juste want the code return null value

Any idea ?

Regards

like image 944
Maryo Avatar asked Aug 22 '16 12:08

Maryo


1 Answers

you can add a custom converter implement Converter<String, OrderOptionEnum> there you implement your own convert logic from string to your enum.

something like this

public class OrderOptionEnumMongoConverter implements Converter<String, OrderOptionEnum> {

    @Override
    public OrderOptionEnum convert(String source) {

        for (OrderOptionEnum OrderOptionEnum : OrderOptionEnum.values()) {
            if (OrderOptionEnum.name().equals(source))
                return OrderOptionEnum;
        }

        return null;
    }
}

Notice !!! This converter will try to convert each string in mongo to your enum, thus may result in unwanted conversions, so make sure you do this only when needed. you can add @ReadingConverter if you want this convert only when reading from mongo.

like image 96
Yoni Avatar answered Nov 19 '22 14:11

Yoni