目的:希望通过枚举,以String形式与数据库对应字段传递,遇到了一些报错,在网上的解决方法大多都解决不了
案发现场(一开始的写法):
报错:,查询的时候数据库的值识别不了,没法赋值给实体类
代码:
/**
* 设备标识.equipment
*/
@Getter
@Setter
@Size(max = 128)
@NotNull
@Comment("设备标识,")
@Column(name = "equipment" , length = 128 , nullable = false)
@Enumerated(EnumType.STRING)
private EquipmentType equipment;
/**
* 枚举:服务器类型
* */
public enum EquipmentType {
/** 0-切片服务器 */
SECTIONS(0, "切片服务器"),
/** 1-其他服务器 */
OTHER(1, "其他服务器");
/** 值 */
private Integer value;
private String label;
/** 取值 */
public String getLabel() { return label; }
public Integer getValue() { return this.value; }
EquipmentType(Integer value, String label) {
this.value = value;
this.label = label;
}
}
分析:
误认为使用了@Enumerated(EnumType.STRING)注解,就相当于分配上面的 label(枚举第二个参数)与数据库交互,在这折腾了好久,其实并非这样。
EnumType源码如下:
枚举类型默认是按他的索引跟数据库关联,也可以指定说他的 value(枚举第一个参数),即第一种ORDINAL(索引)。
第二种是以枚举的value值跟数据库关联,如上面的实体类的SECTION、OTHER
总结:
也就要么存的是它的索引,即ordinal,要么是value值,如SECTION、OTHER
于是枚举代码改成:
/**
* 枚举:服务器类型
* */
public enum EquipmentType {
/** 0-切片服务器 */
切片服务器(0, "切片服务器"),
/** 1-其他服务器 */
其他服务器(1, "其他服务器");
/** 值 */
private Integer value;
private String label;
/** 取值 */
public String getLabel() { return label; }
public Integer getValue() { return this.value; }
EquipmentType(Integer value, String label) {
this.value = value;
this.label = label;
}
}
这样实体类和数据库关联起来
遇到的报错:
解决:去掉size的限定
/**
* 设备标识.equipment
*/
@Getter
@Setter
@NotNull
@Comment("设备标识,")
@Column(name = "equipment" , nullable = false)
@Enumerated(EnumType.STRING)
private EquipmentType equipment;