标签:project hash catch row ota incr oat long github
基本表的增删改查: 1.表结构: CREATE TABLE `t_checkitem` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` varchar(16) DEFAULT NULL, `name` varchar(32) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `age` varchar(32) DEFAULT NULL, `price` float DEFAULT NULL, `type` char(1) DEFAULT NULL COMMENT ‘查检项类型,分为检查和检验两种‘, `attention` varchar(128) DEFAULT NULL, `remark` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=97 DEFAULT CHARSET=utf8 COMMENT=‘体检检查项‘; 2.前端: //钩子函数,VUE对象初始化完成后自动执行 created() { this.findPage(); }, methods: { //编辑 handleEdit() { //表单校验 this.$refs[‘dataEditForm‘].validate((valid)=>{ if(valid){ //表单校验通过,发送请求 axios.post("/checkitem/edit.do",this.formData).then((response)=> { //隐藏编辑窗口 this.dialogFormVisible4Edit = false; if(response.data.flag){ //编辑成功,弹出成功提示信息 this.$message({ message: response.data.message, type: ‘success‘ }); }else{ //编辑失败,弹出错误提示信息 this.$message.error(response.data.message); } }).finally(()=> { //重新发送请求查询分页数据 this.findPage(); }); }else{ //表单校验失败 this.$message.error("表单数据校验失败"); return false; } }); }, //添加 handleAdd () { //校验表单是否合法 this.$refs[‘dataAddForm‘].validate((valid)=>{ if (valid){ axios.post("/checkitem/add.do",this.formData).then((response)=>{ //隐藏新增窗口 this.dialogFormVisible = false; if (response.data.flag){ this.$message({ message: response.data.message, type: ‘success‘ }); }else { this.$message.error(response.data.message); } }).finally(()=>{ this.findPage(); }); }else { this.$message.error("表单数据校验失败"); return false; } }); }, //分页查询 findPage() { //分页参数 var param = { currentPage:this.pagination.currentPage,//页码 pageSize:this.pagination.pageSize,//每页显示的记录数 queryString:this.pagination.queryString//查询条件 }; //请求后台 axios.post("/checkitem/findPage.do",param).then((response)=> { //为模型数据赋值,基于VUE的双向绑定展示到页面 this.dataList = response.data.rows; this.pagination.total = response.data.total; }); // axios.post("/checkitem/findAll.do").then((response)=>{ // // 返回Result(flag,message,data),vue调用的时候,需要在response的后面添加一个data,然后再调用对象属性 // this.dataList = response.data.data // // 提示 // if(response.data.flag){ // this.$message({ // type:"success", // message:response.data.message // }) // }else{ // this.$message({ // type:"error", // message:response.data.message // }) // } // }).catch((error)=>{ // // }) }, // 重置表单 resetForm() { this.formData = {}; }, // 弹出添加窗口 handleCreate() { // 弹出el-dialog的对话框,即新增窗口 this.resetForm(); this.dialogFormVisible = true; }, // 弹出编辑窗口 handleUpdate(row) { //alert(row.id) axios.get("/checkitem/findById.do?id="+ row.id).then((response)=>{ if(response.data.flag){ //设置编辑窗口属性,dialogFormVisible4Edit为true表示显示 this.dialogFormVisible4Edit = true; //为模型数据设置值,基于VUE双向数据绑定回显到页面 this.formData = response.data.data; }else{ this.$message.error(response.data.message); } }); }, //切换页码 handleCurrentChange(currentPage) { this.pagination.currentPage=currentPage; this.findPage(); }, // 删除 handleDelete(row) { // alert(row.id); this.$confirm(‘此操作将永久删除该数据, 是否继续?‘, ‘提示‘, { confirmButtonText: ‘确定‘, cancelButtonText: ‘取消‘, type: ‘warning‘, center: true }).then(() => { // 选择“确定” axios.get("/checkitem/delete.do?id="+row.id).then((response)=>{ // 定义返回Result(flag,message,data) if(response.data.flag){ this.$message({ type: ‘success‘, message: response.data.message }); }else{ this.$message({ type: ‘error‘, message: response.data.message }); } }).catch((error)=>{ this.showError(error); }).finally(()=>{ // 刷新页面 this.findPage(); }) }).catch(() => { // 选择“取消” this.$message({ type: ‘info‘, message: ‘已取消删除‘ }); }); }, showError(e){ // console.log(e); if(e == ‘Error: Request failed with status code 403‘){ this.$message.error("权限不足,拒绝访问!"); return; }else{ this.$message.error("未知错误!"); return; } } } }) </script> 3.后端: package com.itheima.health.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.itheima.health.constant.MessageConstant; import com.itheima.health.entity.PageResult; import com.itheima.health.entity.QueryPageBean; import com.itheima.health.entity.Result; import com.itheima.health.pojo.CheckItem; import com.itheima.health.service.CheckItemService; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @ClassName CheckItemContoller * @Description TODO * @Author ly * @Company 深圳黑马程序员 * @Date 2020/2/13 16:04 * @Version V1.0 */ @RestController @RequestMapping(value = "/checkitem") public class CheckItemContoller { @Reference// 订阅 dubbo注解 CheckItemService checkItemService; // 查询所有 @RequestMapping(value = "/findAll") public Result findAll(){ List<CheckItem> list = checkItemService.findAll(); if(list!=null && list.size()>0){ return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS,list); }else{ return new Result(false, MessageConstant.QUERY_CHECKGROUP_FAIL); } } //新增检查项 @RequestMapping("/add") @PreAuthorize(value = "hasAuthority(‘CHECKITEM_ADD‘)") public Result add(@RequestBody CheckItem checkItem){ try { checkItemService.add(checkItem); return new Result(true,MessageConstant.ADD_CHECKITEM_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new Result(false,MessageConstant.ADD_CHECKITEM_FAIL); } } //分页查询 @RequestMapping("/findPage") @PreAuthorize(value = "hasAuthority(‘CHECKITEM_QUERY‘)") public PageResult findPage(@RequestBody QueryPageBean queryPageBean){ PageResult pageResult = checkItemService.pageQuery( queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString()); return pageResult; } //删除 @RequestMapping("/delete") @PreAuthorize(value = "hasAuthority(‘CHECKITEM_DELETE123‘)") public Result delete(Integer id){ try { checkItemService.delete(id); return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS); }catch (RuntimeException e){ return new Result(false,e.getMessage()); }catch (Exception e){ return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL); } } //编辑(先根据id查询数据再编辑修改) // 跳转到检查项编辑页面 @RequestMapping("/findById") public Result findById(Integer id){ CheckItem checkItem = checkItemService.findById(id); if(checkItem!=null){ return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,checkItem); } else{ return new Result(false,MessageConstant.QUERY_CHECKITEM_FAIL); } } //编辑保存 @RequestMapping("/edit") @PreAuthorize(value = "hasAuthority(‘CHECKITEM_EDIT‘)") public Result edit(@RequestBody CheckItem checkItem){ try { checkItemService.edit(checkItem); return new Result(true,MessageConstant.EDIT_CHECKITEM_SUCCESS); }catch (Exception e){ return new Result(false,MessageConstant.EDIT_CHECKITEM_FAIL); } } } Service: package com.itheima.health.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.health.dao.CheckItemDao; import com.itheima.health.entity.PageResult; import com.itheima.health.pojo.CheckItem; import com.itheima.health.service.CheckItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @ClassName CheckItemServiceImpl * @Description TODO * @Author ly * @Company 深圳黑马程序员 * @Date 2020/2/13 16:03 * @Version V1.0 */ @Service // dubbo提供 @Transactional public class CheckItemServiceImpl implements CheckItemService { @Autowired CheckItemDao checkItemDao; @Override public List<CheckItem> findAll() { List<CheckItem> list = checkItemDao.findAll(); return list; } @Override public void add(CheckItem checkItem) { checkItemDao.add(checkItem); } @Override public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) { //初始化数据 PageHelper.startPage(currentPage,pageSize); //查询返回page Page<CheckItem> page = checkItemDao.selectByCondition(queryString); //封装成PageResult return new PageResult(page.getTotal(),page.getResult()); } @Override public void delete(Integer id) { //查询当前检查项是否和检查组关联 long count = checkItemDao.findCountByCheckItemId(id); if(count > 0){ //当前检查项被引用,不能删除 throw new RuntimeException("当前检查项被检查组引用,不能删除"); } checkItemDao.deleteById(id); } @Override public CheckItem findById(Integer id) { CheckItem checkItem = checkItemDao.findCheckItemById(id); return checkItem; } @Override public void edit(CheckItem checkItem) { checkItemDao.edit(checkItem); } } SQL: <?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.itheima.health.dao.CheckItemDao"> <!--查询所有--> <select id="findAll" resultType="checkitem"> select * from t_checkitem </select> <!--新增检查项--> <insert id="add" parameterType="com.itheima.health.pojo.CheckItem"> insert into t_checkitem(code,name,sex,age,price,type,remark,attention) values (#{code},#{name},#{sex},#{age},#{price},#{type},#{remark},#{attention}) </insert> <!--分页查询--> <select id="selectByCondition" parameterType="String" resultType="com.itheima.health.pojo.CheckItem"> select * from t_checkitem <where> <if test="value != null and value.length > 0"> AND code = #{value} or name = #{value} </if> </where> </select> <!--根据检查项id查询中间关系表--> <select id="findCountByCheckItemId" resultType="long" parameterType="int"> select count(*) from t_checkgroup_checkitem where checkitem_id = #{checkitem_id} </select> <!--删除--> <delete id="deleteById" parameterType="int"> delete from t_checkitem where id = #{id} </delete> <!--修改--> <!--根据检查项id查询检查项信息--> <select id="findCheckItemById" resultType="com.itheima.health.pojo.CheckItem" parameterType="int"> select * from t_checkitem where id = #{id} </select> <!--编辑,如果表单中传递空值,则不更新该字段的值,仍然保留数据库表之前的值--> <update id="edit" parameterType="com.itheima.health.pojo.CheckItem"> update t_checkitem <set> <if test="code!=null and code.length>0"> code=#{code}, </if> <if test="name!=null and name.length>0"> name=#{name}, </if> <if test="sex!=null and sex.length>0"> sex=#{sex}, </if> <if test="age!=null and age.length>0"> age=#{age}, </if> <if test="price!=null"> price=#{price}, </if> <if test="type!=null and type.length>0"> type=#{type}, </if> <if test="remark!=null and remark.length>0"> remark=#{remark}, </if> <if test="attention!=null and attention.length>0"> attention=#{attention}, </if> </set> where id = #{id} </update> <!--使用检查组id,查询检查项的集合--> <select id="findCheckItemListByCheckGroupId" parameterType="int" resultType="checkitem"> SELECT * FROM t_checkitem WHERE id IN (SELECT checkitem_id FROM t_checkgroup_checkitem WHERE checkgroup_id = #{checkGroupId}) </select> </mapper> 多表:
CREATE TABLE `t_setmeal` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(128) DEFAULT NULL, `code` varchar(8) DEFAULT NULL, `helpCode` varchar(16) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `age` varchar(32) DEFAULT NULL, `price` float DEFAULT NULL, `remark` varchar(128) DEFAULT NULL, `attention` varchar(128) DEFAULT NULL, `img` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT=‘体检套餐‘; CREATE TABLE `t_checkgroup` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` varchar(32) DEFAULT NULL, `name` varchar(32) DEFAULT NULL, `helpCode` varchar(32) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `remark` varchar(128) DEFAULT NULL, `attention` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COMMENT=‘体检检查组‘; 中间表: CREATE TABLE `t_setmeal_checkgroup` ( `setmeal_id` int(11) NOT NULL DEFAULT ‘0‘, `checkgroup_id` int(11) NOT NULL DEFAULT ‘0‘, PRIMARY KEY (`setmeal_id`,`checkgroup_id`), KEY `checkgroup_key` (`checkgroup_id`), CONSTRAINT `checkgroup_key` FOREIGN KEY (`checkgroup_id`) REFERENCES `t_checkgroup` (`id`), CONSTRAINT `setmeal_key` FOREIGN KEY (`setmeal_id`) REFERENCES `t_setmeal` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.前端: <script> var vue = new Vue({ el: ‘#app‘, data:{ autoUpload:true,//自动上传 imageUrl:null,//模型数据,用于上传图片完成后图片预览 activeName:‘first‘,//添加/编辑窗口Tab标签名称 pagination: {//分页相关属性 currentPage: 1, pageSize:10, total:100, queryString:null, }, dataList: [],//列表数据 formData: {},//表单数据 tableData:[],//添加表单窗口中检查组列表数据 checkgroupIds:[],//添加表单窗口中检查组复选框对应id dialogFormVisible: false,//控制添加窗口显示/隐藏 dialogFormVisible4Edit:false//控制编辑窗口显示/隐藏 }, created() { this.findPage(); }, methods: { //handleAvatarSuccess:文件上传成功后的钩子,response为服务端返回的值,file为当前上传的文件封装成的js对象 // 使用ElementUI中的upload(response),此时和axios的响应(response.data)是不一样的 handleAvatarSuccess(response, file) { // 返回Result(flag,message,data) if(response.flag){ // 赋值imageUrl(imageUrl=”七牛云空间”+UUID的方式生成文件名) this.imageUrl = "http://q5vtd58my.bkt.clouddn.com/"+response.data; // 赋值img属性的值(UUID生成的文件名),用于套餐保存 this.formData.img = response.data; // 成功的提示 this.$message({ type:"success", message:response.message }) }else{ // 成功的提示 this.$message({ type:"error", message:response.message }) } }, //上传图片之前执行 beforeAvatarUpload(file) { const isJPG = file.type === ‘image/jpeg‘; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error(‘上传套餐图片只能是 JPG 格式!‘); } if (!isLt2M) { this.$message.error(‘上传套餐图片大小不能超过 2MB!‘); } return isJPG && isLt2M; }, //添加 handleAdd () { axios.post("/setmeal/add.do?checkgroupIds="+this.checkgroupIds,this.formData).then((response)=>{ // 返回Result(flag,message,data) if(response.data.flag){ // 关闭新增窗口 this.dialogFormVisible = false; // 成功的提示 this.$message({ type:"success", message:response.data.message }) }else{ // 失败的提示 this.$message({ type:"error", message:response.data.message }) } }).catch((error)=>{ }).finally(()=>{ // 刷新页面 this.findPage(); }) }, //分页查询 findPage() { // 封装QueryPageBean var params = { "currentPage":this.pagination.currentPage, "pageSize":this.pagination.pageSize, "queryString":this.pagination.queryString }; axios.post("/setmeal/findPage.do",params).then((response)=> { // 响应PageResult this.pagination.total = response.data.total; this.dataList = response.data.rows; }).catch((error)=>{ }) }, // 重置表单 resetForm() { // 重置套餐表单 this.formData = {}; // 重置选项卡,始终让选项卡在第一个上 this.activeName = "first"; // 重置第二个选项卡的复选框 this.checkgroupIds = []; // 重置图片的imageUrl this.imageUrl = null; }, // 弹出添加窗口 handleCreate() { //弹出窗口 this.dialogFormVisible = true; // 重置表单 this.resetForm(); //初始化检查组 axios.post("/checkgroup/findAll.do").then((response)=> { if (response.data.flag){ this.tableData = response.data.data; }else{ this.$message.error(response.data.message); } }).catch((error)=>{ }) }, //切换页码 handleCurrentChange(currentPage) { this.pagination.currentPage = currentPage; this.findPage(); }, // 弹出编辑窗口 handleUpdate(row) { // alert(row.id); this.dialogFormVisible4Edit = true; // 重置选项卡,在第一个选项卡上 this.activeName = "first"; //回显套餐数据 axios.get("/setmeal/findById.do?id="+row.id).then((response)=>{ if (response.data.flag){ // 返回Result(flag,message,data),data:Setmeal对象 this.formData=response.data.data; //回显表单中的图片 this.imageUrl = "http://q5vtd58my.bkt.clouddn.com/"+response.data.data.img; //查询检查组列表 axios.get("/checkgroup/findAll.do").then((response)=>{ // 返回Result(flag,message,data),data:List<CheckGroup> if (response.data.flag){ this.tableData = response.data.data; // 3:当前套餐具有的复选框被选中 axios.get("/setmeal/findCheckGroupIdsBySetmealId.do?id="+row.id).then((response)=>{ this.checkgroupIds=response.data; }).catch((error)=>{ this.$message.error(response.data.message); }) } else { this.$message.error(response.data.message); } }).catch((error)=>{ }) }else { this.$message.error(response.data.message); } }).catch((error)=>{ }) }, //编辑 handleEdit() { //编辑保存 axios.post("/setmeal/edit.do?checkgroupIds="+this.checkgroupIds,this.formData).then((response)=> { // 返回Result(flag,message,data) if(response.data.flag){ // 关闭编辑窗口 this.dialogFormVisible4Edit = false; // 成功提示 this.$message({ type:"success", message:response.data.message }) }else { // 错误提示 this.$message({ type:"error", message:response.data.message }) } }).catch((error)=>{ }).finally(()=>{ this.findPage(); }) }, // 删除 handleDelete(row) { // alert(row.id); this.$confirm(‘此操作将永久删除该数据, 是否继续?‘, ‘提示‘, { confirmButtonText: ‘确定‘, cancelButtonText: ‘取消‘, type: ‘warning‘, center: true }).then(() => { // 选择“确定” axios.get("/setmeal/delete.do?id="+row.id).then((response)=>{ // 返回Result(flag,message,data) if(response.data.flag){ this.$message({ type: ‘success‘, message: response.data.message }); }else{ this.$message({ type: ‘error‘, message: response.data.message }); } }).catch((error)=>{ }).finally(()=>{ // 刷新页面 this.findPage(); }) }).catch(() => { // 选择“取消” this.$message({ type: ‘info‘, message: ‘已取消删除‘ }); }); } } }) </script> 后端: package com.itheima.health.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.itheima.health.constant.MessageConstant; import com.itheima.health.constant.RedisPicConstant; import com.itheima.health.entity.PageResult; import com.itheima.health.entity.QueryPageBean; import com.itheima.health.entity.Result; import com.itheima.health.pojo.Setmeal; import com.itheima.health.service.SetmealService; import com.itheima.health.utils.QiniuUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import redis.clients.jedis.JedisPool; import java.util.List; import java.util.UUID; /** * @ClassName CheckItemContoller * @Description TODO * @Author ly * @Company 深圳黑马程序员 * @Date 2020/2/13 16:04 * @Version V1.0 */ @RestController @RequestMapping(value = "/setmeal") public class SetmealContoller { @Reference// 订阅 dubbo注解 SetmealService setmealService; @Autowired JedisPool jedisPool; // 上传 @RequestMapping(value = "/upload") public Result upload(MultipartFile imgFile){ try { // * 实现将图片存放到七牛云上 // 参数一:字节数组(springmvc的方式),使用imgFile.getBytes() // 参数二:上传文件名(唯一) // 获取上传的文件名(1.jpg) String originalFilename = imgFile.getOriginalFilename(); // 使用UUID的方式生成文件名 String fileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf(".")); // * 实现将图片存放到七牛云上 QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName); // (1)Redis的集合存储,上传图片的时候,将图片名称,存放到Redis中一份(key值setmeal_pic_resource),然后再上传到七牛云上 jedisPool.getResource().sadd(RedisPicConstant.SETMEAL_PIC_RESOURCE,fileName); // UUID的方式生成文件名,并返回 return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.PIC_UPLOAD_FAIL); } } // 保存 @RequestMapping(value = "/add") public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){ try { setmealService.add(setmeal,checkgroupIds); return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.ADD_SETMEAL_FAIL); } } // 分页查询 @RequestMapping(value = "/findPage") public PageResult findPage(@RequestBody QueryPageBean queryPageBean){ PageResult pageResult = setmealService.findPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString()); return pageResult; } // ID查询 @RequestMapping(value = "/findById") public Result findById(Integer id){ Setmeal setmeal = setmealService.findById(id); if(setmeal!=null){ return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal); } else{ return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL); } } // 使用套餐ID,查询检查组ID的集合 @RequestMapping(value = "/findCheckGroupIdsBySetmealId") public List<Integer> findCheckGroupIdsBySetmealId(Integer id){ List<Integer> list = setmealService.findCheckGroupIdsBySetmealId(id); return list; } // 编辑保存 @RequestMapping(value = "/edit") public Result edit(@RequestBody Setmeal setmeal, Integer [] checkgroupIds){ try { setmealService.edit(setmeal,checkgroupIds); return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.EDIT_SETMEAL_FAIL); } } // 删除 @RequestMapping(value = "/delete") public Result delete(Integer id){ try { setmealService.delete(id); return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS); }catch (RuntimeException e) { e.printStackTrace(); return new Result(false, e.getMessage()); }catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.DELETE_SETMEAL_FAIL); } } } Service: package com.itheima.health.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.health.constant.MessageConstant; import com.itheima.health.constant.RedisPicConstant; import com.itheima.health.dao.CheckGroupDao; import com.itheima.health.dao.CheckItemDao; import com.itheima.health.dao.SetmealDao; import com.itheima.health.entity.PageResult; import com.itheima.health.pojo.Setmeal; import com.itheima.health.service.SetmealService; import com.itheima.health.utils.QiniuUtils; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import redis.clients.jedis.JedisPool; import java.io.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName CheckItemServiceImpl * @Description TODO * @Author ly * @Company 深圳黑马程序员 * @Date 2020/2/13 16:03 * @Version V1.0 */ @Service // dubbo提供 @Transactional public class SetmealServiceImpl implements SetmealService { @Autowired SetmealDao setmealDao; // 检查组 @Autowired CheckGroupDao checkGroupDao; // 检查项 @Autowired CheckItemDao checkItemDao; @Autowired JedisPool jedisPool; @Override public void add(Setmeal setmeal, Integer[] checkgroupIds) { // 1:保存套餐 setmealDao.add(setmeal); // 2:建立套餐和检查组的关联关系,向中间表保存数据 setSetmealAndCheckGruop(setmeal.getId(),checkgroupIds); // (2)Redis的集合存储,保存套餐数据图片的时候,将图片名称,存放到Redis中一份(key值setmeal_pic_db_resource),然后在保存到数据库 jedisPool.getResource().sadd(RedisPicConstant.SETMEAL_PIC_DB_RESOURCE,setmeal.getImg()); // 生成静态页面(通过WEB-INF/ftl/下的flt文件)(输出到healthmobile_web下的webapp/pages下) this.generateMobileStaticHtml(); } private void generateMobileStaticHtml() { // 查询所有套餐(从数据库查询) List<Setmeal> list = this.findAll(); // 生成套餐列表的静态页面 this.generateMobileSetmealListStaticHtml(list); // 生成套餐详情的静态页面 this.generateMobileSetmealDetailStaticHtml(list); } private void generateMobileSetmealDetailStaticHtml(List<Setmeal> list) { if(list!=null && list.size()>0){ for (Setmeal setmeal : list) { Map<String,Object> map = new HashMap<>(); map.put("setmeal",this.findById(setmeal.getId())); // 使用套餐id,查询套餐的详情(包括检查组的集合和检查项的集合) // 生成静态页面(参数1:静态页面的ftl文件名,参数2:静态页面的名称,参数三:map) useFreeMarkerGenerateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map); } } } @Autowired FreeMarkerConfigurer freeMarkerConfigurer; @Value("${out_put_path}") private String output_path; // 等同于加载D:\\ideaProjects\\85\\health_parent\\healthmobile_web\\src\\main\\webapp\\pages private void useFreeMarkerGenerateHtml(String s, String s1, Map<String, Object> map) { // 第一步:创建一个 Configuration 对象 Configuration configuration = freeMarkerConfigurer.getConfiguration(); Writer writer = null; try { // 第二步:加载一个模板,创建一个模板对象。 Template template = configuration.getTemplate(s); // 第三步:创建Writer对象,加载D:\\ideaProjects\\85\\health_parent\\healthmobile_web\\src\\main\\webapp\\pages\\m_setmeal.html writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(output_path+"\\"+s1)))); // 第四步:调用模板对象的 process 方法输出文件(格式,定义html)。 template.process(map,writer); } catch (Exception e) { e.printStackTrace(); } finally { //第八步:关闭流。 try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } private void generateMobileSetmealListStaticHtml(List<Setmeal> list) { Map<String,Object> map = new HashMap<>(); map.put("setmealList",list); // 生成静态页面(参数1:静态页面的ftl文件名,参数2:静态页面的名称,参数三:map) useFreeMarkerGenerateHtml("mobile_setmeal.ftl","m_setmeal.html",map); } @Override public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) { PageHelper.startPage(currentPage,pageSize); Page<Setmeal> page = setmealDao.findPage(queryString); return new PageResult(page.getTotal(),page.getResult()); } // @Override // public Setmeal findById(Integer id) { // // 1:使用id查询套餐信息 // Setmeal setmeal = setmealDao.findById(id); // // 2:查询检查组集合的信息,封装到套餐对象中的checkGroups的集合属性中 // List<CheckGroup> checkGroups = checkGroupDao.findCheckGroupListBySetmealId(setmeal.getId()); // setmeal.setCheckGroups(checkGroups); // // 3:查询检查项集合的信息,封装到检查组对象中的checkItems的集合属性中 // if(checkGroups!=null && checkGroups.size()>0){ // for (CheckGroup checkGroup : checkGroups) { // List<CheckItem> checkItems = checkItemDao.findCheckItemListByCheckGroupId(checkGroup.getId()); // checkGroup.setCheckItems(checkItems); // 封装检查组中的检查项集合 // } // } // setmeal.setCheckGroups(checkGroups); // 封装套餐中的检查组集合 // return setmeal; // } //利用ResultMap来映射 @Override public Setmeal findById(Integer id) { // 1:使用id查询套餐信息 Setmeal setmeal = setmealDao.findById(id); return setmeal; } @Override public List<Integer> findCheckGroupIdsBySetmealId(Integer id) { return setmealDao.findCheckGroupIdsBySetmealId(id); } @Override public void edit(Setmeal setmeal, Integer[] checkgroupIds) { // 建议最后操作数据库,先操作其他服务器内容(删除七牛云上的图片) // 判断是否改变的图片名称 // (1)使用套餐id,查询套餐 Setmeal setmeal_db = setmealDao.findById(setmeal.getId()); // (2)获取数据库的套餐图片名称 String img_db = setmeal_db.getImg(); // (3)判断是否改变图片名称 if(setmeal.getImg()!=null && !setmeal.getImg().equals(img_db)){ // 如果改变套餐图片的名称,需要做处理 // 删除之前七牛云上的存放图片 QiniuUtils.deleteFileFromQiniu(img_db); // 删除Redis中key值是SETMEAL_PIC_RESOURCE的图片名称 jedisPool.getResource().srem(RedisPicConstant.SETMEAL_PIC_RESOURCE,img_db); // 删除Redis中key值是SETMEAL_PIC_DB_RESOURCE的图片名称 jedisPool.getResource().srem(RedisPicConstant.SETMEAL_PIC_DB_RESOURCE,img_db); // 添加Redis中key值是SETMEAL_PIC_DB_RESOURCE的新的图片名称 jedisPool.getResource().sadd(RedisPicConstant.SETMEAL_PIC_DB_RESOURCE,setmeal.getImg()); } // 1:编辑保存套餐 setmealDao.edit(setmeal); // 2:删除套餐和检查组中间表的数据 setmealDao.deleteSetmealAndCheckGroupBySetmealId(setmeal.getId()); // 3:重新新增套餐和检查组中间表的数据,建立关联关系 this.setSetmealAndCheckGruop(setmeal.getId(),checkgroupIds); // 生成静态页面(通过WEB-INF/ftl/下的flt文件)(输出到healthmobile_web下的webapp/pages下) this.generateMobileStaticHtml(); } @Override public void delete(Integer id) { // 判断当前套餐是否和检查组之间存在关联关系 Long count = setmealDao.findSetmealAndCheckGroupCountBySetmealId(id); // 查询获取到数据 if(count>0){ throw new RuntimeException(MessageConstant.GET_SETMEALANDCHECKGROUPERROR); } // 如果可以删除 // 先删除七牛云上的图片 // 使用套餐id,查询套餐 Setmeal setmeal_db = setmealDao.findById(id); // 获取删除的图片名称 String img_db = setmeal_db.getImg(); // 七牛云删除图片 if(img_db!=null && !"".equals(img_db)){ // 删除七牛云上图片 QiniuUtils.deleteFileFromQiniu(img_db); // 删除Redis中key值是SETMEAL_PIC_RESOURCE的图片名称 jedisPool.getResource().srem(RedisPicConstant.SETMEAL_PIC_RESOURCE,img_db); // 删除Redis中key值是SETMEAL_PIC_DB_RESOURCE的图片名称 jedisPool.getResource().srem(RedisPicConstant.SETMEAL_PIC_DB_RESOURCE,img_db); } // 再使用id,删除套餐 setmealDao.delete(id); // 生成静态页面(通过WEB-INF/ftl/下的flt文件)(输出到healthmobile_web下的webapp/pages下) this.generateMobileStaticHtml(); } @Override public List<Setmeal> findAll() { List<Setmeal> list = setmealDao.findAll(); return list; } @Override public List<Map> findOrderCountBySetmealName() { List<Map> list = setmealDao.findOrderCountBySetmealName(); return list; } private void setSetmealAndCheckGruop(Integer setmealId, Integer[] checkgroupIds) { if(checkgroupIds!=null && checkgroupIds.length>0){ for (Integer checkGroupId : checkgroupIds) { // 使用Map Map map = new HashMap(); map.put("setmealId",setmealId); map.put("checkGroupId",checkGroupId); setmealDao.addSetmealAndCheckGroup(map); } } } } SQL: <?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.itheima.health.dao.SetmealDao"> <!--保存套餐,返回套餐id--> <insert id="add" parameterType="setmeal"> <selectKey resultType="int" order="AFTER" keyProperty="id"> select last_insert_id() </selectKey> insert into t_setmeal(name,code,helpCode,sex,age,price,remark,attention,img) values(#{name},#{code},#{helpCode},#{sex},#{age},#{price},#{remark},#{attention},#{img}) </insert> <!--保存套餐和检查组的中间表--> <insert id="addSetmealAndCheckGroup" parameterType="map"> insert into t_setmeal_checkgroup(setmeal_id,checkgroup_id) values(#{setmealId},#{checkGroupId}) </insert> <!--条件的查询--> <select id="findPage" parameterType="String" resultType="setmeal"> select * from t_setmeal <if test="value!=null and value.length>0"> where name like concat(‘%‘,#{value},‘%‘) or code = #{value} or helpCode = #{value } </if> </select> <!--映射数据库的字段和实体类的属性--> <resultMap id="setmealMap" type="Setmeal"> <!--映射id字段--> <id column="id" property="id"></id> <!--映射普通字段--> <result column="name" property="name"></result> <result column="code" property="code"></result> <result column="helpCode" property="helpCode"></result> <result column="sex" property="sex"></result> <result column="age" property="age"></result> <result column="price" property="price"></result> <result column="remark" property="remark"></result> <result column="attention" property="attention"></result> <result column="img" property="img"></result> <!--映射集合List property="":映射的实体类型属性 column="":传递条件id的字段(需求:使用套餐id,查询检查组的集合List<CheckGroup>,封装到checkGroups的属性中) select="":指定Dao的查询方法 --> <collection property="checkGroups" column="id" select="com.itheima.health.dao.CheckGroupDao.findCheckGroupListBySetmealId"></collection> </resultMap> <!--ID查询--> <select id="findById" parameterType="int" resultMap="setmealMap"> select * from t_setmeal where id = #{id} </select> <!--使用套餐ID,查询检查组的ID集合--> <select id="findCheckGroupIdsBySetmealId" parameterType="int" resultType="int"> select checkgroup_id from t_setmeal_checkgroup where setmeal_id = #{setmealId} </select> <!--编辑保存套餐--> <update id="edit" parameterType="setmeal"> update t_setmeal <set> <if test="name!=null and name.length>0"> name = #{name}, </if> <if test="code!=null and code.length>0"> code = #{code}, </if> <if test="helpCode!=null and helpCode.length>0"> helpCode = #{helpCode}, </if> <if test="sex!=null and sex.length>0"> sex = #{sex}, </if> <if test="age!=null and age.length>0"> age = #{age}, </if> <if test="price!=null"> price = #{price}, </if> <if test="remark!=null and remark.length>0"> remark = #{remark}, </if> <if test="attention!=null and attention.length>0"> attention = #{attention}, </if> <if test="img!=null and img.length>0"> img = #{img}, </if> </set> where id = #{id} </update> <!--使用套餐id,删除套餐和检查组中间表的数据--> <delete id="deleteSetmealAndCheckGroupBySetmealId" parameterType="int"> delete from t_setmeal_checkgroup where setmeal_id = #{setmealId} </delete> <!--使用套餐id,删除套餐--> <delete id="delete" parameterType="int"> delete from t_setmeal where id = #{id} </delete> <!--使用套餐id,查询套餐和检查组的中间表,判断是否存在数据--> <select id="findSetmealAndCheckGroupCountBySetmealId" parameterType="int" resultType="long"> select count(*) from t_setmeal_checkgroup where setmeal_id = #{setmealId} </select> <!--查询所有套餐--> <select id="findAll" resultType="setmeal"> select * from t_setmeal </select> <!--统计分组,根据套餐统计预约数量--> <select id="findOrderCountBySetmealName" resultType="map"> SELECT s.name,COUNT(*) value FROM t_order o,t_setmeal s WHERE o.setmeal_id = s.id GROUP BY s.name </select> </mapper>
标签:project hash catch row ota incr oat long github
原文地址:https://www.cnblogs.com/lyle-liu/p/12892701.html