Skip to content
广告❤️成为赞助商

Automatic Enum Mapping

MongoPlus provides flexible enum mapping. By simply declaring an enum, you can achieve automatic mapping. Unspecified enums are mapped using their name.

java
public class User {
    private String name; // Name
    private AgeEnum age; // Age
    private GradeEnum grade; // Grade
}

Create a Mapper and Register as a Bean

java
import com.mongoplus.annotation.comm.EnumValue;
import com.mongoplus.mapping.FieldInformation;
import com.mongoplus.strategy.mapping.MappingStrategy;
import com.mongoplus.toolkit.EnumUtil;

/**
 * Enum mapping strategy
 *
 * Author: anwen
 */
@SuppressWarnings({"rawtypes"})
@Component
public class EnumMappingStrategy implements MappingStrategy<Enum> {

    @Override
    public Object mapping(Enum fieldValue) throws IllegalAccessException {
        FieldInformation fieldInformation = EnumUtil.getFieldInformation(fieldValue);
        if (fieldInformation == null) {
            return fieldValue.name();
        }
        EnumValue enumValue = fieldInformation.getAnnotation(EnumValue.class);
        if (enumValue.valueStore()){
            return fieldInformation.getValue(fieldValue);
        }
        return fieldValue.name();
    }
}

Enum Declaration

Use the @EnumValue annotation on enum properties to specify the actual value stored in the database. Any field of the enum class can be used, such as an index or code.

java
@Getter
@AllArgsConstructor
public enum GradeEnum {
    PRIMARY(1, "Primary School"),
    SECONDARY(2, "Middle School"),
    HIGH(3, "High School");

    @EnumValue // Marks that the database stores the 'code' value
    private final int code;
    // Other attributes...
}

With these simple steps, you can elegantly use enum properties in MongoPlus, and easily serialize enum values into the format required by the frontend.