skip to Main Content

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


    • To save an enum as an integer in MongoDB using Spring Boot, you can
      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:

    public class StatusConverter implements Converter<Status, Integer> {
    
    @Override
    public Integer convert(Status source) {
        return source.getValue();
    }
    
    @Override
    public Status unwrap(Integer source) {
        return Arrays.stream(Status.values())
                .filter(status -> status.getValue() == source)
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Invalid status value: " + source));
    }
    }
    

    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

    Login or Signup to reply.
  1. I am not sure, but you can try this

        @Enumerated(EnumType.ORDINAL)
        private Status status;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search