如果你的实体字段是一个枚举类型,而在数据表里是整型,这时需要进行处理。我本次是用在查询,从mysql的int类型字段映射到枚举类型。
添加枚举处理器
@MappedJdbcTypes(JdbcType.INTEGER)
@MappedTypes(value = ElectricProtectConfigType.class)
public class ElectricProtectConfigTypeHandler extends BaseTypeHandler<ElectricProtectConfigType> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, ElectricProtectConfigType electricProtectConfigType, JdbcType jdbcType) throws SQLException {
if (electricProtectConfigType == null) {
return;
}
preparedStatement.setInt(i, electricProtectConfigType.getCode());
}
@Override
public ElectricProtectConfigType getNullableResult(ResultSet resultSet, String s) throws SQLException {
if (resultSet.wasNull())
return null;
return ElectricProtectConfigType.of(resultSet.getInt(s));
}
@Override
public ElectricProtectConfigType getNullableResult(ResultSet resultSet, int i) throws SQLException {
if (resultSet.wasNull())
return null;
return ElectricProtectConfigType.of(resultSet.getInt(i));
}
@Override
public ElectricProtectConfigType getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
if (callableStatement.wasNull())
return null;
return ElectricProtectConfigType.of(callableStatement.getInt(i));
}
}
在配置文件指定处理器所在的包
mybatis-plus:
type-handlers-package: com.bdht.iot.entity.handler
定义枚举
public interface DescEnum {
Integer getCode();
String getDesc();
}
@IotSetting("电子围栏类型")
public enum ElectricProtectConfigType implements DescEnum {
@IotEnum
CIRCLE(0, "圆形"),
@IotEnum
POLYGON(1, "多边形"),
@IotEnum
RECTANGLE(2, "矩形"),
@IotEnum
ROAD(3, "路段"),
@IotEnum
NONE(9, "无");
private Integer code;
private String desc;
ElectricProtectConfigType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public static String getDesc(ElectricProtectConfigType pattern) {
return pattern.getDesc();
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getDesc() {
return desc;
}
@JsonCreator
public static ElectricProtectConfigType of(Integer value) {
for (ElectricProtectConfigType enumItem : ElectricProtectConfigType.values()) {
if (enumItem.getCode().equals(value)) {
return enumItem;
}
}
throw new IllegalArgumentException("未知枚举值");
}
}
在实体类中引用枚举
@Data
@TableName(value = "lbs_electric_protect_config", autoResultMap = true)
public class ElectricFenceEntity implements Serializable {
private static final long serialVersionUID = -1656007095179506678L;
@TableId
private Long id;
private String name;
@TableField(typeHandler = ElectricProtectConfigTypeHandler.class)
//电子围栏类型[1:圆形:circle,2:多边形: polygon]
private ElectricProtectConfigType type;
}
枚举转换失败总结
实体类上添加注解@TableName(autoResultMap = true)
实体的枚举字段上,添加注解@TableField(typeHandler = ElectricProtectConfigTypeHandler.class)
配置文件添加mybatis-plus.typeHandlersPackage: com.bdht.iot.entity.handler