I have a project with Spring Boot and MongoDB. I have an enum class that return Integer. But, as far as i know, enum types saved as String into mongdb. But, i want to saved as Integer. How can i handle this problem.?
Below code my Employee class.
@Data
@Document
public class Employee {
@MongoId(FieldType.OBJECT_ID)
private String id;
private String name;
private String surname;
private String department;
private Address address;
private Company company;
private Status status;
}
Below code my enum class.
public enum Status {
JUNIOR(0),
MID(1),
SENIOR(2);
private final int value;
Status(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
2
Answers
use a custom converter
To create a custom converter for your enum, you need to create a
class that implements the Converter interface and takes your enum
class as the generic type parameter. The following code shows an
example of a custom converter for the Status enum:
Once you have created your custom converter, you need to register it with Spring Data MongoDB. You can do this by adding the following configuration to your application’s spring.data.MongoDB properties:
spring.data.mongodb.converters.enabled=true
spring.data.mongodb.converters.custom-converters=com.example.StatusConverter
I am not sure, but you can try this