Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

java - MongoDB integer field to Enum conversion

I have a class that contained a Long value, that actually only had three possible numbers 1,2,3.

public class ASD {
    ...
    private Long downloadType;
}

I changed it to:

public class ASD {
    ...
    private DownloadType downloadType;
}

public enum DownloadType {
    @JsonProperty("1")
    IMAGE,
    @JsonProperty("2")
    TEXT,
    @JsonProperty("3")
    BOTH;
}

When I try to get the entity ASD from the database(Mongo) it comes as integer, and it tries to make a conversion of Enum.valueOf("1"). There's no enum of value 1, and it throws this exception.

java.lang.IllegalArgumentException: No enum constant com.example.domain.enums.DownloadType.1
at java.lang.Enum.valueOf(Enum.java:238) ~[na:1.8.0_251]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getPotentiallyConvertedSimpleRead(MappingMongoConverter.java:829) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]

I have tried to use the @Enumerated annotation, make a custom converter that implements AttributeConverter(but it seems that this only works for sql databases).

I have seen solutions where you can convert a number into an Enum. But the conversion will try with EVERY number.

Any idea of how to make a custom converter for this enum?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...