自3.1.0開始,如果你無需使用原生枚舉,可配置默認(rèn)枚舉來省略掃描通用枚舉配置
3.1.0 以下版本改變了原生默認(rèn)行為,升級時請將默認(rèn)枚舉設(shè)置為?EnumOrdinalTypeHandler
?
實體中使用原生枚舉
配置枚舉包掃描的時候能提前注冊使用注解枚舉的緩存
@EnumValue
? 注解枚舉屬性public enum GradeEnum {
PRIMARY(1, "小學(xué)"), SECONDORY(2, "中學(xué)"), HIGH(3, "高中");
GradeEnum(int code, String descp) {
this.code = code;
this.descp = descp;
}
@EnumValue//標(biāo)記數(shù)據(jù)庫存的值是code
private final int code;
//。。。
}
IEnum
接口如下:public enum AgeEnum implements IEnum<Integer> {
ONE(1, "一歲"),
TWO(2, "二歲"),
THREE(3, "三歲");
private int value;
private String desc;
@Override
public Integer getValue() {
return this.value;
}
}
public class User {
/**
* 名字
* 數(shù)據(jù)庫字段: name varchar(20)
*/
private String name;
/**
* 年齡,IEnum接口的枚舉處理
* 數(shù)據(jù)庫字段:age INT(3)
*/
private AgeEnum age;
/**
* 年級,原生枚舉(帶{@link com.baomidou.mybatisplus.annotation.EnumValue}):
* 數(shù)據(jù)庫字段:grade INT(2)
*/
private GradeEnum grade;
}
resources/application.yml
?mybatis-plus:
# 支持統(tǒng)配符 * 或者 ; 分割
typeEnumsPackage: com.baomidou.springboot.entity.enums
....
MybatisPlusAutoConfiguration
?
@Configuration
public class MybatisPlusAutoConfiguration {
@Bean
public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
return properties -> {
GlobalConfig globalConfig = properties.getGlobalConfig();
globalConfig.setBanner(false);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
properties.setConfiguration(configuration);
};
}
}
toString
?方法springboot:
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer(){
return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
}
jackson:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
以上兩種方式任選其一,然后在枚舉中復(fù)寫 ?toString
方法即可。
public enum GradeEnum {
PRIMARY(1, "小學(xué)"), SECONDORY(2, "中學(xué)"), HIGH(3, "高中");
GradeEnum(int code, String descp) {
this.code = code;
this.descp = descp;
}
@EnumValue
@JsonValue //標(biāo)記響應(yīng)json值
private final int code;
}
toString
方法全局處理方式
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteEnumUsingToString);
局部處理方式
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
private UserStatus status;
以上兩種方式任選其一,然后在枚舉中復(fù)寫 ?toString
方法即可。
更多建議: