1Controller类:
1.1controller基类:
BaseCrudController

package com.invt.common.controller; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.invt.api.util.ApiUtil; import com.invt.common.constants.OperateEnum; import com.invt.common.constants.PublicConstants; import com.invt.common.constants.StatusEnum; import com.invt.common.http.HttpSender; import com.invt.common.mvc.ControllerHelper; import com.invt.common.service.BaseCrudService; import com.invt.common.util.ImportAndExportUtil; import com.invt.common.util.SimplePage; import com.invt.device.entity.Device; import com.invt.mgdb.entity.OpRecord; import com.invt.mgdb.service.IOpRecordService; import com.invt.terminal.entity.TerminalGroup; import com.invt.terminal.entity.TerminalType; import com.invt.topic.entity.TopicGrant; import com.invt.topic.service.ITopicGrantService; import com.invt.user.entity.Account; import com.invt.user.service.IModuleOpGrantService; /** * */ public abstract class BaseCrudController<ModelType> extends ControllerHelper { private BaseCrudService service; private CrudInfo crudInfo; @Resource protected ApiUtil apiUtil; @Resource private IOpRecordService opRecordService; @Resource private IModuleOpGrantService moduleOpGrantService; @Resource private ITopicGrantService topicGrantService; @PostConstruct protected void initConfig() { this.crudInfo = this.init(); this.service = crudInfo.getService(); } @Resource private HttpSender httpSender; protected abstract CrudInfo init(); /*@RequestMapping(value = "/importGards.json", method=RequestMethod.POST) @ResponseBody public Map<String, Object> importGards(HttpServletRequest req, ModelType modelType) throws Exception { int pageSize =500; String result=""; Map<String, Object> params = builderParams(req, modelType); // 请求参数默认加上当前用户Id,以及当前用户的权限组编码 Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER); Map<String, Object> obj = new HashMap<String, Object>(); if(null!=user && user.getOpGroupCode().equals("1002")){//超级管理员 params.put("createUser", user.getId()); params.put("curOpGroupCode", user.getOpGroupCode()); int total = this.service.findCount(params); result=importGardsData(modelType,pageSize,total,params); }else{ result="非管理员无此权限"; } obj.put("result", result); return obj; } @RequestMapping(value = "/importIwoCloud.json", method=RequestMethod.POST) @ResponseBody public Map<String, Object> importIwoCloud(HttpServletRequest req, ModelType modelType) throws Exception { int limit=1000000,page=1,type=3; long count=0; int ret = -1; StringBuffer sb=new StringBuffer(""); if(modelType instanceof TerminalGroup) type=1; if(modelType instanceof TerminalType) type=2; String return_sult= null; String result=ImportAndExportUtil.sendPostrRegister(limit,page,type);//从gards查询所有数据 JSONObject jsonObject =null; Map<String, Object> obj = new HashMap<String, Object>(); if(null!=result){ jsonObject= JSONObject.parseObject(result); ret=jsonObject.getIntValue("ret"); } if(ret==0){ JSONArray jsonArray=jsonObject.getJSONArray("rows"); for (int i = 0; i < jsonArray.size(); i++) {//导入iwocloud fillModelType(req,modelType,jsonArray.getJSONObject(i));//拼装数据 Object apiObj = this.combineApiData(req, modelType, OperateEnum.ADD.getValue());// 组装api对象数据 Map<String, Object> returnMap = callApihandle(apiObj, this.crudInfo.getApiMethodName() + "." + OperateEnum.ADD.getValue()); if ((Boolean) returnMap.get("success")) {//向云平台注册成功,插入本地数据库 try { modelTypeVerify(req,modelType,OperateEnum.ADD.getValue());//拼装数据,Device需设置分组、类型id this.service.add(modelType); saveOperateRecord(req, modelType, OperateEnum.ADD.getText());// 记录日志 } catch (Exception e) {//操作mysql数据库异常删除api,确保数据一致 if(0==SearchParams(modelType)){//如果数据库已存在,视为成功 }else{//不存在,则为异常 callApihandle(apiObj, this.crudInfo.getApiMethodName() + "." + OperateEnum.DELETE.getValue()); sb.append("导入数据库数据 id:"+jsonArray.getJSONObject(i).getString("id")+" 失败,检查数据库中是否存在\n"); count++; } } }else{ sb.append("导入云平台数据 id:"+jsonArray.getJSONObject(i).getString("id")+" 失败, "+returnMap.get("msg")+"\n"); count++; } } if(count>0){ return_sult="共 "+count+" 条数据导入失败 \n"+sb.toString(); } }else{//获取数据失败 return_sult="从Gards获取数据失败!\n"; } obj.put("result", return_sult); return obj; }*/ public int SearchParams(ModelType modelType){ return 0; } public void fillModelType(HttpServletRequest req,ModelType modelType, JSONObject jsonObject) {} public void modelTypeVerify(HttpServletRequest req,ModelType modelType, String operate){}//分组和类型不需要(不用设置id) public String importGardsData(ModelType type,int pageSize,int total,Map<String, Object> params){ return null; } @RequestMapping(value = "/list.json") @ResponseBody public Map<String, Object> queryList(HttpServletRequest req, ModelType modelType) throws Exception { int pageNo = StringUtils.isEmpty(req.getParameter("page")) ? 1 : Integer.parseInt(req.getParameter("page")); int pageSize = StringUtils.isEmpty(req.getParameter("rows")) ? 20 : Integer.parseInt(req.getParameter("rows")); String sortColumn = StringUtils.isEmpty(req.getParameter("sort")) ? "" : String.valueOf(req.getParameter("sort")); String sortOrder = StringUtils.isEmpty(req.getParameter("order")) ? "" : String.valueOf(req.getParameter("order")); Map<String, Object> params = builderParams(req, modelType); // 请求参数默认加上当前用户Id,以及当前用户的权限组编码 Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER); Map<String, Object> obj = new HashMap<String, Object>(); if(user!=null){ if(user.getOpGroupCode().equals("1003")){//普通用户查看管理员下的数据(分组、类型、终端,主题,授权) params.put("createUser", user.getCreateUser()); }else{ params.put("createUser", user.getId()); } params.put("curOpGroupCode", user.getOpGroupCode()); int total = this.service.findCount(params); SimplePage page = new SimplePage(pageNo, pageSize, (int) total); List<ModelType> list = this.service.findByPage(page, sortColumn, sortOrder, params); obj.put("total", total); obj.put("rows", list); } return obj; } public Map<String, Object> builderParams(HttpServletRequest req, ModelType modelType) { Map<String, Object> retParams = new HashMap<String, Object>(req.getParameterMap().size()); Map<String, String[]> params = req.getParameterMap(); if (null != params && params.size() > 0) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Entry<String, String[]> p : params.entrySet()) { if (null == p.getValue() || StringUtils.isEmpty(p.getValue().toString())) continue; String values[] = (String[]) p.getValue();// 获取参数值 String match = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\\d):[0-5]?\\d:[0-5]?\\d$"; if (1 == values.length && values[0].matches(match)) { try { retParams.put(p.getKey(), sdf.parse(values[0])); } catch (ParseException e) { retParams.put(p.getKey(), values[0]); e.printStackTrace(); } } else if (2 == values.length) { retParams.put(p.getKey(), values); } else { retParams.put(p.getKey(), values[0]); } } } return retParams; } @RequestMapping(value = "/get_count.json") public ResponseEntity<Integer> getCount(HttpServletRequest req, ModelType modelType) throws Exception { Map<String, Object> params = builderParams(req, modelType); int total = this.service.findCount(params); return new ResponseEntity<Integer>(total, HttpStatus.OK); } @RequestMapping(value = "/list.do") public ModelAndView list(HttpServletRequest req, ModelType modelType) { ModelAndView mv = new ModelAndView(); int pageNo = StringUtils.isEmpty(req.getParameter("page")) ? 1 : Integer.parseInt(req.getParameter("page")); int pageSize = StringUtils.isEmpty(req.getParameter("rows")) ? 20 : Integer.parseInt(req.getParameter("rows")); String sortColumn = StringUtils.isEmpty(req.getParameter("sort")) ? "" : String.valueOf(req.getParameter("sort")); String sortOrder = StringUtils.isEmpty(req.getParameter("order")) ? "" : String.valueOf(req.getParameter("order")); Map<String, Object> params = builderParams(req, modelType);// 构建参数 // 请求参数默认加上当前用户Id,以及当前用户的权限组编码 Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER); if(user!=null){ if(user.getOpGroupCode().equals("1003")){//普通用户查看管理员下的数据(分组、类型、终端,主题,授权) params.put("createUser", user.getCreateUser()); }else{ params.put("createUser", user.getId()); } params.put("curOpGroupCode", user.getOpGroupCode()); int total = this.service.findCount(params); SimplePage page = new SimplePage(pageNo, pageSize, (int) total); List<ModelType> list = this.service.findByPage(page, sortColumn, sortOrder, params); mv.addObject("total", total);// 总记录数 mv.addObject("rows", list);// 内容 mv.addObject("curPageNo", pageNo);// 当前页 mv.addObject("showPageList", page.getShowPageList());// 当前显示页列表 mv.addObject("totalPage", page.getTotalPage());// 总页数 mv.addObject("params", params);// 查询参数 mv.setViewName(crudInfo.ftlFolder + "list"); /* * if(modelType instanceof Device){//设备数据api链接 * mv.addObject("dataApiUrl",dataApiUrl); } */ mv.addObject("havedOp", handerHavedOpGrant(req, user));// 处理操作权限 } return mv; } @RequestMapping(value = "/get.do") public ResponseEntity<ModelType> get(HttpServletRequest req, ModelType modelType) throws Exception { ModelType type = service.findById(modelType); return new ResponseEntity<ModelType>(type, HttpStatus.OK); } @RequestMapping(value = "/get_list.do") @ResponseBody public List<ModelType> getList(HttpServletRequest req, ModelType modelType) throws Exception { Map<String, Object> params = builderParams(req, modelType); // 请求参数默认加上当前用户Id,以及当前用户的权限组编码 Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER); if(user!=null){ if(user.getOpGroupCode().equals("1003")){//普通用户查看管理员下的数据(分组、类型、终端,主题,授权) params.put("createUser", user.getCreateUser()); }else{ params.put("createUser", user.getId()); } params.put("curOpGroupCode", user.getOpGroupCode()); } return this.service.findByParams(params); } @RequestMapping(value = "/add.do") public ResponseEntity<Map<String, Object>> add(HttpServletRequest req, ModelType type) throws Exception { if (type instanceof TopicGrant) { ((TopicGrant) type).setId(String.valueOf(topicGrantService.selectNextId())); } Object apiObj = combineApiData(req, type, OperateEnum.ADD.getValue());// 组装api对象数据 Map<String, Object> returnMap = callApihandle(apiObj, this.crudInfo.getApiMethodName() + "." + OperateEnum.ADD.getValue()); fillInitValue(req, type, OperateEnum.ADD.getValue()); if ((Boolean) returnMap.get("success")) {// 增加 try { this.service.add(type); } catch (Exception e) {// 操作mysql数据库异常删除api callApihandle(apiObj, this.crudInfo.getApiMethodName() + "." + OperateEnum.DELETE.getValue()); throw new Exception(e); } saveOperateRecord(req, type, OperateEnum.ADD.getText());// 记录日志 } return new ResponseEntity<Map<String, Object>>(returnMap, HttpStatus.OK); } @RequestMapping(value = "/update.do") public ResponseEntity<Map<String, Object>> moditfy(HttpServletRequest req, ModelType type) throws Exception { Map<String, Object> returnMap = callApihandle(combineApiData(req, type, OperateEnum.UPDATE.getValue()), this.crudInfo.getApiMethodName() + "." + OperateEnum.UPDATE.getValue()); fillInitValue(req, type, OperateEnum.UPDATE.getValue()); if ((Boolean) returnMap.get("success")) {// 修改 service.modifyById(type); saveOperateRecord(req, type, OperateEnum.UPDATE.getText());// 记录日志 } return new ResponseEntity<Map<String, Object>>(returnMap, HttpStatus.OK); } @RequestMapping(value = "/delete.do") public ResponseEntity<Map<String, Object>> remove(HttpServletRequest req, ModelType type) throws Exception { Map<String, Object> returnMap = callApihandle(combineApiData(req, type, OperateEnum.DELETE.getValue()), this.crudInfo.getApiMethodName() + "." + OperateEnum.DELETE.getValue()); fillInitValue(req, type, OperateEnum.DELETE.getValue()); if ((Boolean) returnMap.get("success")) {// 刪除 // service.modifyById(type); ModelType dbType = service.findById(type); service.deleteById(Integer.valueOf(req.getParameter("id"))); saveOperateRecord(req, dbType, OperateEnum.DELETE.getText());// 记录日志 } return new ResponseEntity<Map<String, Object>>(returnMap, HttpStatus.OK); } /** * 填充初始化值,比如创建人、修改人(可以重写) * * @param req * @param type * @throws Exception */ public void fillInitValue(HttpServletRequest req, ModelType type, String operate) throws Exception { // 增加创建人和修改人 Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER);// 获取当前用户 if(user!=null){ Class<ModelType> tc = (Class<ModelType>) type.getClass(); if ("add".equals(operate)) { Method setCreateM = tc.getMethod("setCreateUser", Integer.class); setCreateM.invoke(type, user.getId()); } if ("delete".equals(operate)) { Method setCreateM = tc.getMethod("setStatus", Integer.class); setCreateM.invoke(type, StatusEnum.Status_DISABLED.getValue()); } Method setUpdateM = tc.getMethod("setUpdateUser", Integer.class); setUpdateM.invoke(type, user.getId()); } } /** * 组装api数据(可以重写) * * @param type * @return */ public Object combineApiData(HttpServletRequest req, ModelType type, String operate) { return null; } /** * 调用api,返回结果 * * @param obj * @return */ public Map<String, Object> callApihandle(Object obj, String url) throws Exception { Map<String, Object> returnMap = new HashMap<String, Object>(); returnMap.put("success", true); if (null == obj) { return returnMap; } apiUtil.setDataObject(obj); apiUtil.getApiResult(url);// 调用api int apiCode = apiUtil.getApiStateCode(); if (apiCode != PublicConstants.API_SUCCESS_FLAG) {// api处理失败 returnMap.put("success", false); returnMap.put("msg", "【" + apiCode + "】" + apiUtil.getApiState()); } return returnMap; } /** * 保存操作记录 * * @param req */ protected void saveOperateRecord(HttpServletRequest req, ModelType type, String operate) throws Exception { Account user = (Account) req.getSession().getAttribute(PublicConstants.SESSION_USER);// 获取当前用户 if(user!=null){ String path = req.getServletPath(); OpRecord or = new OpRecord(); //new add for recode userId and createUserId by lijun 2017.1.9 or.setUserId(user.getId()); if(user.getOpGroupCode().equals("1003")||user.getOpGroupCode().equals("1002")){//normal user or.setCreateUserId(user.getCreateUser()); }else{ or.setCreateUserId(user.getId()); } //end or.setAccount(user.getAccount());// 用户名 or.setModule(path);// 模块 or.setOperate(operate);// 操作描述 or.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));// 时间 or.setIp(getIpAddr(req));// ip if (null != type) {// 赋值详细 or.setDetail(JSON.toJSONString(type, SerializerFeature.WriteMapNullValue)); } this.opRecordService.save(or); } } /** * 处理操作权限 * * @param req * @param user * @return */ private String handerHavedOpGrant(HttpServletRequest req, Account user) { Map<String, Object> params = new HashMap<String, Object>(); if(user!=null){ params.put("curOpGroupCode", user.getOpGroupCode());// 当前的权限组代码 params.put("reqUrl", req.getServletPath()); params.put("status", StatusEnum.Status_ENABLED.getValue()); } return this.moduleOpGrantService.queryModuleHavedGrant(params); } private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (!StringUtils.isEmpty(ip) && ip.split("\\.").length != 4) { ip = "未知";// ip为0:0:0:0:0:0:0:1的处理 } return ip; } public class CrudInfo { public CrudInfo(String jspFolder, BaseCrudService service) { super(); this.ftlFolder = jspFolder; this.service = service; } public CrudInfo(String jspFolder, BaseCrudService service, String apiMethodName) { super(); this.ftlFolder = jspFolder; this.service = service; this.apiMethodName = apiMethodName; } private String ftlFolder; private BaseCrudService service; private String apiMethodName; public String getFtlFolder() { return ftlFolder; } public void setFtlFolder(String ftlFolder) { this.ftlFolder = ftlFolder; } public BaseCrudService getService() { return service; } public void setService(BaseCrudService service) { this.service = service; } public String getApiMethodName() { return apiMethodName; } public void setApiMethodName(String apiMethodName) { this.apiMethodName = apiMethodName; } } }
1.2controller具体实现类

package com.invt.system.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.invt.common.constants.PublicConstants; import com.invt.common.controller.BaseCrudController; import com.invt.common.util.SimplePage; import com.invt.device.entity.Device; import com.invt.mgdb.entity.OpRecord; import com.invt.mgdb.service.IOpRecordService; import com.invt.system.service.ISysMonitorService; import com.invt.user.entity.Account; @Controller @RequestMapping("/sys_monitor") @Scope("prototype") public class SysMonitorController extends BaseCrudController<Device> { private static Logger logger = LoggerFactory.getLogger(SysMonitorController.class); @Resource private ISysMonitorService sysMonitorService; @Resource private IOpRecordService opRecordService; @Override protected CrudInfo init() { return new CrudInfo("sys_monitor/", sysMonitorService, "monitor"); } @RequestMapping(value = "/olist.do") public ModelAndView sysMonitorList(HttpServletRequest req) { ModelAndView mv = new ModelAndView(); int pageNo = StringUtils.isEmpty(req.getParameter("page")) ? 1 : Integer.parseInt(req.getParameter("page")); int pageSize = StringUtils.isEmpty(req.getParameter("rows")) ? 20 : Integer.parseInt(req.getParameter("rows")); String sortColumn = StringUtils.isEmpty(req.getParameter("sort")) ? "" : String.valueOf(req.getParameter("sort")); String sortOrder = StringUtils.isEmpty(req.getParameter("order")) ? "" : String.valueOf(req.getParameter("order")); Map<String, Object> params = builderParams(req, null);// 构建参数 Account user=(Account) req.getSession().getAttribute(PublicConstants.SESSION_USER); // by lijun 2017.1.9 if(user!=null){ params.put("userId", user.getId()); params.put("curOpGroupCode", user.getOpGroupCode()); }//end int total = this.opRecordService.findCount(params); SimplePage page = new SimplePage(pageNo, pageSize, (int) total); List<OpRecord> list = this.opRecordService.findByPage(page, sortColumn, sortOrder, params); mv.addObject("total", total);// 总记录数 mv.addObject("rows", list);// 内容 mv.addObject("curPageNo", pageNo);// 当前页 mv.addObject("showPageList", page.getShowPageList());// 当前显示页列表 mv.addObject("totalPage", page.getTotalPage());// 总页数 mv.addObject("params", params);//查询参数 mv.setViewName("sys_monitor/list"); return mv; } }
2 Service类
2.1service基类
接口类:

package com.invt.common.service; import java.util.List; import java.util.Map; import com.invt.common.util.SimplePage; public abstract interface BaseCrudService { public abstract <ModelType> int deleteById(int id); public abstract <ModelType> int add(ModelType paramModelType); public abstract <ModelType> ModelType findById(ModelType paramModelType); public abstract <ModelType> int modifyById(ModelType paramModelType); public abstract int findCount(Map<String, Object> paramMap); public abstract <ModelType> List<ModelType> findByPage(SimplePage paramSimplePage, String paramString1, String paramString2, Map<String, Object> paramMap); public abstract <ModelType> List<ModelType> findByParams(Map<String, Object> paramMap); }
接口实现类:

package com.invt.common.service.impl; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import com.invt.common.dao.BaseCrudDao; import com.invt.common.service.BaseCrudService; import com.invt.common.util.SimplePage; public abstract class BaseCrudServiceImpl implements BaseCrudService { private BaseCrudDao dao; @PostConstruct private void initConfig() { this.dao = init(); } public abstract BaseCrudDao init(); public <ModelType> int deleteById(int id) { return this.dao.deleteByPrimaryKey(id); } public <ModelType> int add(ModelType modelType) { return this.dao.insertSelective(modelType); } public <ModelType> ModelType findById(ModelType modelType) { return this.dao.selectByPrimaryKey(modelType); } public <ModelType> List<ModelType> findByParams(Map<String, Object> params) { return this.dao.selectByParams(params); } public <ModelType> int modifyById(ModelType modelType) { return this.dao.updateByPrimaryKeySelective(modelType); } public int findCount(Map<String, Object> params) { return this.dao.selectCount(params); } public <ModelType> List<ModelType> findByPage(SimplePage page, String orderByField, String orderBy, Map<String, Object> params) { return this.dao.selectByPage(page, orderByField, orderBy, params); } }
2.2service具体实现类
接口类:

package com.invt.system.service; import com.invt.common.service.BaseCrudService; public interface ISysMonitorService extends BaseCrudService{ }
接口实现类:

package com.invt.system.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.invt.common.dao.BaseCrudDao; import com.invt.common.service.impl.BaseCrudServiceImpl; import com.invt.system.dao.SysMonitorDao; import com.invt.system.service.ISysMonitorService; @Service("sysMonitorService") public class SysMonitorServiceImpl extends BaseCrudServiceImpl implements ISysMonitorService { @Resource private SysMonitorDao sysMonitorDao; @Override public BaseCrudDao init() { return sysMonitorDao; } }
3 dao类
3.1dao基类

package com.invt.common.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.invt.common.util.SimplePage; public abstract interface BaseCrudDao { public abstract <ModelType> int insert(ModelType paramModelType); public abstract <ModelType> int insertSelective(ModelType paramModelType); public abstract <ModelType> ModelType selectByPrimaryKey(ModelType paramModelType); public abstract <ModelType> int updateByPrimaryKeySelective(ModelType paramModelType); public abstract <ModelType> int updateByPrimaryKey(ModelType paramModelType); public abstract int selectCount(@Param("params") Map<String, Object> paramMap); public abstract <ModelType> List<ModelType> selectByPage(@Param("page") SimplePage paramSimplePage, @Param("orderByField") String paramString1, @Param("orderBy") String paramString2, @Param("params") Map<String, Object> paramMap); public abstract int deleteByPrimaryKey(int paramInt); public abstract <ModelType> List<ModelType> selectByParams(@Param("params") Map<String, Object> params); }
3.2dao具体实现类

package com.invt.system.dao; import com.invt.common.dao.BaseCrudDao; public interface SysMonitorDao extends BaseCrudDao{ }
mybatis xml文件

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.invt.user.dao.AccountDao"> <resultMap id="BaseResultMap" type="com.invt.user.entity.Account"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="account" property="account" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="op_group_code" property="opGroupCode" jdbcType="VARCHAR" /> <result column="stime" property="stime" jdbcType="TIMESTAMP" /> <result column="etime" property="etime" jdbcType="TIMESTAMP" /> <result column="mqtt_account" property="mqttAccount" jdbcType="VARCHAR" /> <result column="mqtt_password" property="mqttPassword" jdbcType="VARCHAR" /> <result column="api_id" property="apiId" jdbcType="VARCHAR" /> <result column="api_key" property="apiKey" jdbcType="VARCHAR" /> <result column="ltime" property="ltime" jdbcType="TIMESTAMP" /> <result column="lcount" property="lcount" jdbcType="INTEGER" /> <result column="description" property="description" jdbcType="VARCHAR" /> <result column="country_id" property="countryId" jdbcType="INTEGER" /> <result column="province_id" property="provinceId" jdbcType="INTEGER" /> <result column="city_id" property="cityId" jdbcType="INTEGER" /> <result column="email" property="email" jdbcType="VARCHAR" /> <result column="phone" property="phone" jdbcType="VARCHAR" /> <result column="login_ip" property="loginIp" jdbcType="VARCHAR" /> <result column="user_style" property="userStyle" jdbcType="VARCHAR" /> <result column="status" property="status" jdbcType="INTEGER" /> <result column="create_user" property="createUser" jdbcType="INTEGER" /> <result column="create_time" property="createTime" jdbcType="TIMESTAMP" /> <result column="update_user" property="updateUser" jdbcType="INTEGER" /> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /> </resultMap> <resultMap id="QueryResultMap" type="com.invt.user.entity.Account" extends="BaseResultMap"> <result column="op_group_name" property="opGroupName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> iwc_account.id, iwc_account.account, iwc_account.password, iwc_account.op_group_code, iwc_account.stime, iwc_account.etime, iwc_account.mqtt_account, iwc_account.mqtt_password, iwc_account.api_id, iwc_account.api_key, iwc_account.ltime, iwc_account.lcount, iwc_account.description, iwc_account.country_id, iwc_account.province_id, iwc_account.city_id, iwc_account.email, iwc_account.phone, iwc_account.login_ip,iwc_account.user_style, iwc_account.status, iwc_account.create_user, iwc_account.create_time, iwc_account.update_user, iwc_account.update_time </sql> <sql id="condition"> <if test="null!=params"> <if test="null==params.statusNotNeed or ''==params.statusNotNeed"> AND iwc_account.status != 0 </if> <if test="null!=params.status and ''!=params.status"> AND iwc_account.status = #{params.status,jdbcType=INTEGER} </if> <if test="null!=params.account and ''!=params.account"> AND iwc_account.account = #{params.account,jdbcType=VARCHAR} </if> <if test="null!=params.nameSearch and ''!=params.nameSearch"> AND iwc_account.account like '%${params.nameSearch}%' </if> <if test="null!=params.opGroupCode and ''!=params.opGroupCode"> AND iwc_account.op_group_code = #{params.opGroupCode,jdbcType=VARCHAR} </if> <if test="null!=params.accountSearch and ''!=params.accountSearch"> AND iwc_account.account like '%${params.accountSearch}%' </if> <if test="null!=params.createUser and ''!=params.createUser and 1 != params.createUser"> AND iwc_account.create_user = #{params.createUser,jdbcType=VARCHAR} </if> <if test="null!=params.mqttAccount and ''!=params.mqttAccount "> AND iwc_account.mqtt_account = #{params.mqttAccount,jdbcType=VARCHAR} </if> <if test="null!=params.apiId and ''!=params.apiId "> AND iwc_account.api_id = #{params.apiId,jdbcType=VARCHAR} </if> </if> </sql> <select id="selectCount" resultType="java.lang.Integer"> select count(1) as s from iwc_account where 1=1 <include refid="condition" /> </select> <select id="selectByPage" resultMap="QueryResultMap" parameterType="map"> select <include refid="Base_Column_List" /> ,iogg.op_group_name from iwc_account left join iwc_op_grant_group iogg on iwc_account.op_group_code=iogg.op_group_code where 1=1 <include refid="condition" /><!-- 不能查看自己本身以及admin用户 --> <if test="null!=params.createUser and ''!=params.createUser"> AND iwc_account.id != #{params.createUser,jdbcType=INTEGER} AND iwc_account.id != 1 </if> <if test="orderByField != null and ''!=orderByField"> ORDER BY ${orderByField} <if test="orderByField"> ${orderBy} </if> </if> LIMIT #{page.startRowNum} ,#{page.pageSize} </select> <select id="selectByParams" resultMap="BaseResultMap" parameterType="map"> select <include refid="Base_Column_List" /> from iwc_account where 1=1 <include refid="condition" /> </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from iwc_account where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from iwc_account where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.invt.user.entity.Account"> insert into iwc_account (id, account, password, op_group_code, stime, etime, mqtt_account, mqtt_password, api_id, api_key, ltime, lcount, description, country_id, province_id, city_id, email, phone, login_ip, status, create_user, create_time, update_user, update_time ) values (#{id,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{opGroupCode,jdbcType=VARCHAR}, #{stime,jdbcType=TIMESTAMP}, #{etime,jdbcType=TIMESTAMP}, #{mqttAccount,jdbcType=VARCHAR}, #{mqttPassword,jdbcType=VARCHAR}, #{apiId,jdbcType=VARCHAR}, #{apiKey,jdbcType=VARCHAR}, #{ltime,jdbcType=TIMESTAMP}, #{lcount,jdbcType=INTEGER}, #{description,jdbcType=VARCHAR}, #{countryId,jdbcType=INTEGER}, #{provinceId,jdbcType=INTEGER}, #{cityId,jdbcType=INTEGER}, #{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{loginIp,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER}, #{createUser,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateUser,jdbcType=INTEGER}, #{updateTime,jdbcType=TIMESTAMP} ) </insert> <insert id="insertSelective" parameterType="com.invt.user.entity.Account"> insert into iwc_account <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="account != null"> account, </if> <if test="password != null"> password, </if> <if test="opGroupCode != null"> op_group_code, </if> <if test="stime != null"> stime, </if> <if test="etime != null"> etime, </if> <if test="mqttAccount != null"> mqtt_account, </if> <if test="mqttPassword != null"> mqtt_password, </if> <if test="apiId != null"> api_id, </if> <if test="apiKey != null"> api_key, </if> <if test="ltime != null"> ltime, </if> <if test="lcount != null"> lcount, </if> <if test="description != null"> description, </if> <if test="countryId != null"> country_id, </if> <if test="provinceId != null"> province_id, </if> <if test="cityId != null"> city_id, </if> <if test="email != null"> email, </if> <if test="phone != null"> phone, </if> <if test="loginIp != null"> login_ip, </if> <if test="status != null"> status, </if> <if test="createUser != null"> create_user, </if> <if test="createTime != null"> create_time, </if> <if test="updateUser != null"> update_user, </if> <if test="updateTime != null"> update_time, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="account != null"> #{account,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="opGroupCode != null"> #{opGroupCode,jdbcType=VARCHAR}, </if> <if test="stime != null"> #{stime,jdbcType=TIMESTAMP}, </if> <if test="etime != null"> #{etime,jdbcType=TIMESTAMP}, </if> <if test="mqttAccount != null"> #{mqttAccount,jdbcType=VARCHAR}, </if> <if test="mqttPassword != null"> #{mqttPassword,jdbcType=VARCHAR}, </if> <if test="apiId != null"> #{apiId,jdbcType=VARCHAR}, </if> <if test="apiKey != null"> #{apiKey,jdbcType=VARCHAR}, </if> <if test="ltime != null"> #{ltime,jdbcType=TIMESTAMP}, </if> <if test="lcount != null"> #{lcount,jdbcType=INTEGER}, </if> <if test="description != null"> #{description,jdbcType=VARCHAR}, </if> <if test="countryId != null"> #{countryId,jdbcType=INTEGER}, </if> <if test="provinceId != null"> #{provinceId,jdbcType=INTEGER}, </if> <if test="cityId != null"> #{cityId,jdbcType=INTEGER}, </if> <if test="email != null"> #{email,jdbcType=VARCHAR}, </if> <if test="phone != null"> #{phone,jdbcType=VARCHAR}, </if> <if test="loginIp != null"> #{loginIp,jdbcType=VARCHAR}, </if> <if test="status != null"> #{status,jdbcType=INTEGER}, </if> <if test="createUser != null"> #{createUser,jdbcType=INTEGER}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateUser != null"> #{updateUser,jdbcType=INTEGER}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.invt.user.entity.Account"> update iwc_account <set> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="opGroupCode != null"> op_group_code = #{opGroupCode,jdbcType=VARCHAR}, </if> <if test="stime != null"> stime = #{stime,jdbcType=TIMESTAMP}, </if> <if test="etime != null"> etime = #{etime,jdbcType=TIMESTAMP}, </if> <if test="mqttAccount != null"> mqtt_account = #{mqttAccount,jdbcType=VARCHAR}, </if> <if test="mqttPassword != null"> mqtt_password = #{mqttPassword,jdbcType=VARCHAR}, </if> <if test="apiId != null"> api_id = #{apiId,jdbcType=VARCHAR}, </if> <if test="apiKey != null"> api_key = #{apiKey,jdbcType=VARCHAR}, </if> <if test="ltime != null"> ltime = #{ltime,jdbcType=TIMESTAMP}, </if> <if test="lcount != null"> lcount = #{lcount,jdbcType=INTEGER}, </if> <if test="description != null"> description = #{description,jdbcType=VARCHAR}, </if> <if test="countryId != null"> country_id = #{countryId,jdbcType=INTEGER}, </if> <if test="provinceId != null"> province_id = #{provinceId,jdbcType=INTEGER}, </if> <if test="cityId != null"> city_id = #{cityId,jdbcType=INTEGER}, </if> <if test="email != null"> email = #{email,jdbcType=VARCHAR}, </if> <if test="phone != null"> phone = #{phone,jdbcType=VARCHAR}, </if> <if test="loginIp != null"> login_ip = #{loginIp,jdbcType=VARCHAR}, </if> <if test="userStyle != null"> user_style = #{userStyle,jdbcType=VARCHAR}, </if> <if test="status != null"> status = #{status,jdbcType=INTEGER}, </if> <if test="createUser != null"> create_user = #{createUser,jdbcType=INTEGER}, </if> <if test="createTime != null"> create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateUser != null"> update_user = #{updateUser,jdbcType=INTEGER}, </if> <if test="updateTime != null"> update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=INTEGER} <if test="null!=account and ''!=account"> AND account = #{account,jdbcType=VARCHAR} </if> </update> <update id="updateByPrimaryKey" parameterType="com.invt.user.entity.Account"> update iwc_account set account = #{account,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, op_group_code = #{opGroupCode,jdbcType=VARCHAR}, stime = #{stime,jdbcType=TIMESTAMP}, etime = #{etime,jdbcType=TIMESTAMP}, mqtt_account = #{mqttAccount,jdbcType=VARCHAR}, mqtt_password = #{mqttPassword,jdbcType=VARCHAR}, api_id = #{apiId,jdbcType=VARCHAR}, api_key = #{apiKey,jdbcType=VARCHAR}, ltime = #{ltime,jdbcType=TIMESTAMP}, lcount = #{lcount,jdbcType=INTEGER}, description = #{description,jdbcType=VARCHAR}, country_id = #{countryId,jdbcType=INTEGER}, province_id = #{provinceId,jdbcType=INTEGER}, city_id = #{cityId,jdbcType=INTEGER}, email = #{email,jdbcType=VARCHAR}, phone = #{phone,jdbcType=VARCHAR}, login_ip = #{loginIp,jdbcType=VARCHAR}, status = #{status,jdbcType=INTEGER}, create_user = #{createUser,jdbcType=INTEGER}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_user = #{updateUser,jdbcType=INTEGER}, update_time = #{updateTime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=INTEGER} </update> <update id="resetUserStatus"> update iwc_account set status=1 where status=2 </update> </mapper>