There are several methods to handle enum value conversion:
- Server-side mapping: Return enum values from backend API endpoints
- Annotation-based conversion: Use MyBatis-Plus annotations for automatic enum handling
Method 1: Implementing IEnum Interface
public enum GenderType implements IEnum<Integer> {
MALE(1, "Male"),
FEMALE(2, "Female");
private final Integer id;
private final String description;
GenderType(Integer id, String description) {
this.id = id;
this.description = description;
}
@Override
public Integer getValue() {
return this.id;
}
}
// Corresponding DTO
public class UserDto {
private Long userId;
private String username;
private GenderType gender;
}
Configuration in application.yml:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
type-enums-package: com.example.enums
Method 2: Using @EnumValue Annotation
public enum UserRole {
ADMIN(1, "Administrator"),
USER(2, "Regular User");
@EnumValue
private final Integer roleId;
private final String roleName;
UserRole(Integer roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
// Getters omitted for brevity
}