需求: 判断同一监控点下监控点名称是否已存在
前端页面:
数据库:
(monitor_type:监控点类型;TeleMeasurement:遥测;TeleQuantity:遥信)
实体类:
@Enumerated(EnumType.STRING)
@Column(name = "monitor_type", length = 30)
private MonitorType monitorType;//监控点类型
枚举类型定义如下:
/**
1. 监控点类型
*/
public enum MonitorType {
TeleMeasurement("遥测"),TeleQuantity("遥信");
private String name;
MonitorType(String name) {
this.name = name;
}
public String getName() {
return name;
}
难点: 监控点类型字段(monitor_type)在实体类中是以枚举类型来保存的
分析: 从选项框选择后从数据库查询选中的监控点类型,由于该字段在实体类中是以枚举类型保存,因此从前端获取到选项框的值也就是枚举类值后需通过该枚举类值去获得它的描述,然后再去数据库中查询。
解决步骤:
1. 获取选项框选中的值
jsp页面代码:
<div class="ftitle">监控点信息</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>监控点类型:</label>
<select id="monitorType" name="monitorType" class="easyui-combobox" data-options="
editable:false" style="width:150px" required="true"
>
<option value="TeleMeasurement">遥测</option>
<option value="TeleQuantity">遥信</option>
</select>
</div>
js获取选项框值并传给控制层:
var type = $("#monitorType").combobox('getText');
$.post( path+'/monitor/monitorExists' , {type:type, name:mName,id:id} , function(r){
if(r){
$.messager.alert("提示","此监控点类型下监控点名已经存在.");
return;
}else{}
},'json');
2. 控制层获取监控点类型的值
//监控点名是否存在
@RequestMapping(value = { "/monitorExists" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
@ResponseBody
public boolean keyExists(HttpServletRequest request) {
String monitorType = request.getParameter("type");
...
Map<String, String> queryMap = new HashMap<String, String>();
queryMap.put("monitorType", monitorType);
...
return this.monitorService.monitorExists(queryMap);
}
3. service层直接调用dao层方法(省略)
4. 枚举类中添加方法,该方法通过枚举类值获得枚举类实例
*/
public enum MonitorType {
TeleMeasurement("遥测"),TeleQuantity("遥信");
private String name;
MonitorType(String name) {
this.name = name;
}
public String getName() {
return name;
}
//通过枚举类值获得枚举类实例
public static MonitorType geMonitorType(String name) {
for(MonitorType type : MonitorType.values()){
if(type.getName().equals(name)){
return type;
}
}
return null;
}
5.dao层查询数据库表
通过 geMonitorType将获取到的枚举值去得到对应的枚举类实例,然后与数据库表中存储的数据进行匹配。
@Override
public boolean monitorExists(Map<String, String> queryMap) {
String name=queryMap.get("name");
...
List<Object> param=new ArrayList<Object>();
StringBuilder s=new StringBuilder("select count(*) from Monitor m where deleted=0");
if (monitorType!=null) {
s.append("and m.monitorType=?");
param.add(MonitorType.geMonitorType(monitorType));
}
...
Integer total=Integer.valueOf(super.executeScalarByParam(s.toString(), param.toArray()).intValue());
return total.intValue() > 0;
}