枚举类
package sh.maixun.tids.res.domain.resourceenum;
import java.util.HashMap;
import java.util.Map;
/**
* @author jiafu
* @since 1.0
*/
public enum ConType {
//金属/非金属/气体/化学品/辅料
金属(0, "金属"),
非金属(1, "非金属"),
气体(2, "气体"),
化学品(3, "化学品"),
辅料(4,"辅料");
private final Integer key;
private final String value;
public Integer getKey() {
return key;
}
public String getValue() {
return value;
}
ConType(Integer key, String value) {
this.key = key;
this.value = value;
}
/**
* 根据key获取value
*
* @param key
* : 键值key
* @return String
*/
public static String getValueByKey(Integer key) {
ConType[] enums = ConType.values();
for (int i = 0; i < enums.length; i++) {
if (enums[i].getKey().equals(key)) {
return enums[i].getValue();
}
}
return "";
}
/**
* 转换为MAP集合
*
* @returnMap<String, String>
*/
public static Map<String, String> toMap() {
Map<String, String> map = new HashMap<String, String>();
ConType[] enums = ConType.values();
for (int i = 0; i < enums.length; i++) {
map.put(enums[i].getKey().toString(), enums[i].getValue());
}
return map;
}
}
实体类
@Entity
@DynamicUpdate
@Table(name = "t_consumable")
@EqualsAndHashCode(callSuper=true)
@Data
public class Consumable extends AbstractRecording<Long, Consumable> {
//物品的类别 金属/非金属/气体/化学品/辅料
@Column(name = "conType")
@Enumerated(EnumType.ORDINAL)
private ConType conType;
}
全局搜索方法
package sh.maixun.tids.res.controller.commonControl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sh.maixun.common.model.ResultModel;
import sh.maixun.common.model.ResultModels;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author jiafu
* @since 1.0
*/
@RestController
@RequestMapping("/${tids.resources.api-prefix:res-api}")
public class ResEnumControl {
@GetMapping("findEnumByName")
public ResultModel findEnumByName(String name) {
try {
String[] names = name.split(",");
Map<String, List<Object>> maps = new HashMap<>();
for (String nm : names) { //nm是自己枚举类的名字
String enumPackage = "sh.maixun.tids.res.domain.resourceenum"; //自己枚举类的包名
Class<Enum> clazz = (Class<Enum>) Class.forName(enumPackage + "." + nm);
Enum[] objs = clazz.getEnumConstants();
Method toMap = clazz.getDeclaredMethod("toMap");
List ls = new ArrayList<Map>();
Map invoke = (Map)toMap.invoke(objs);
ls.add(invoke);
maps.put(nm, ls);
}
return ResultModels.success("枚举解析成功",null, maps);
} catch (Exception e) {
return ResultModels.fail("枚举解析失败");
}
}
}
查询该枚举的列表
保存后查询