黑馬程序員-傳智健康項目(第三章)


傳智健康項目


第3章 預約管理-檢查組管理

1. 需求分析

檢查組其實就是多個檢查項的集合,例如有一個檢查組為“一般檢查”,這個檢查組可以包括多個檢查項:身高、體重、收縮壓、舒張壓等。所以在添加檢查組時需要選擇這個檢查組包括的檢查項。

檢查組對應的實體類為CheckGroup,對應的數據表為t_checkgroup。檢查組和檢查項為多對多關系,所以需要中間表t_checkgroup_checkitem進行關聯。

2. 新增檢查組

2.1 完善頁面

檢查組管理頁面對應的是checkgroup.html頁面,根據產品設計的原型已經完成了頁面基本結構的編寫,現在需要完善頁面動態效果。

2.1.1 彈出新增窗口

頁面中已經提供了新增窗口,只是出於隱藏狀態。只需要將控制展示狀態的屬性dialogFormVisible改為true即可顯示出新增窗口。點擊新建按鈕時綁定的方法為handleCreate,所以在handleCreate方法中修改dialogFormVisible屬性的值為true即可。同時為了增加用戶體驗度,需要每次點擊新建按鈕時清空表單輸入項。

由於新增檢查組時還需要選擇此檢查組包含的檢查項,所以新增檢查組窗口分為兩部分信息:基本信息和檢查項信息,如下圖:

新建按鈕綁定單擊事件,對應的處理函數為handleCreate

<el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
// 重置表單
resetForm() {
	this.formData = {};
},
// 彈出添加窗口
handleCreate() {
	this.resetForm();
	this.dialogFormVisible = true;
}

2.1.2 動態展示檢查項列表

現在雖然已經完成了新增窗口的彈出,但是在檢查項信息標簽頁中需要動態展示所有的檢查項信息列表數據,並且可以進行勾選。具體操作步驟如下:

(1)定義模型數據

tableData:[],//新增和編輯表單中對應的檢查項列表數據
checkitemIds:[],//新增和編輯表單中檢查項對應的復選框,基於雙向綁定可以進行回顯和數據提交

(2)動態展示檢查項列表數據,數據來源於上面定義的tableData模型數據

<table class="datatable">
  <thead>
    <tr>
      <th>選擇</th>
      <th>項目編碼</th>
      <th>項目名稱</th>
      <th>項目說明</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="c in tableData">
      <td>
        <input :id="c.id" v-model="checkitemIds" type="checkbox" :value="c.id">
      </td>
      <td><label :for="c.id">{{c.code}}</label></td>
      <td><label :for="c.id">{{c.name}}</label></td>
      <td><label :for="c.id">{{c.remark}}</label></td>
    </tr>
  </tbody>
</table>

(3)完善handleCreate方法,發送ajax請求查詢所有檢查項數據並將結果賦值給tableData模型數據用於頁面表格展示

// 彈出添加窗口
handleCreate() {
  this.dialogFormVisible = true;
  this.resetForm();
  //默認切換到第一個標簽頁(基本信息)
  this.activeName='first';
  //重置
  this.checkitemIds = [];
  //發送ajax請求查詢所有檢查項信息
  axios.get("/checkitem/findAll.do").then((res)=> {
    if(res.data.flag){
      //將檢查項列表數據賦值給模型數據用於頁面表格展示
      this.tableData = res.data.data;
    }else{
      this.$message.error(res.data.message);
    }
  });
}

(4)分別在CheckItemController、CheckItemService、CheckItemServiceImpl、CheckItemDao、CheckItemDao.xml中擴展方法查詢所有檢查項數據

CheckItemController:

//查詢所有
@RequestMapping("/findAll")
public Result findAll(){
  List<CheckItem> checkItemList = checkItemService.findAll();
  if(checkItemList != null && checkItemList.size() > 0){
    Result result = new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS);
    result.setData(checkItemList);
    return result;
  }
  return new Result(false,MessageConstant.QUERY_CHECKITEM_FAIL);
}

CheckItemService:

public List<CheckItem> findAll();

CheckItemServiceImpl:

public List<CheckItem> findAll() {
  return checkItemDao.findAll();
}

CheckItemDao:

public List<CheckItem> findAll();

CheckItemDao.xml:

<select id="findAll" resultType="com.itheima.pojo.CheckItem">
  select * from t_checkitem
</select>

2.1.3 提交請求

當用戶點擊新增窗口中的確定按鈕時發送ajax請求將數據提交到后台進行數據庫操作。提交到后台的數據分為兩部分:檢查組基本信息(對應的模型數據為formData)和檢查項id數組(對應的模型數據為checkitemIds)。

為確定按鈕綁定單擊事件,對應的處理函數為handleAdd

<el-button type="primary" @click="handleAdd()">確定</el-button>

完善handleAdd方法

// 彈出添加窗口
//添加
handleAdd () {
  //發送ajax請求將模型數據提交到后台處理
  axios.post(
    		"/checkgroup/add.do?checkitemIds=" + this.checkitemIds,
    		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();
  });
}

2.2 后台代碼

2.2.1 Controller

在health_backend工程中創建CheckGroupController

package com.itheima.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
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;
/**
 * 檢查組管理
 */
@RestController
@RequestMapping("/checkgroup")
public class CheckGroupController {
    @Reference
    private CheckGroupService checkGroupService;

    //新增
    @RequestMapping("/add")
    public Result add(@RequestBody CheckGroup checkGroup,Integer[] checkitemIds){
        try {
            checkGroupService.add(checkGroup,checkitemIds);
        }catch (Exception e){
            //新增失敗
            return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL);
        }
        //新增成功
        return new Result(true,MessageConstant.ADD_CHECKGROUP_SUCCESS);
    }
}

2.2.2 服務接口

在health_interface工程中創建CheckGroupService接口

package com.itheima.service;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import java.util.List;
/**
 * 檢查組服務接口
 */
public interface CheckGroupService {
    void add(CheckGroup checkGroup,Integer[] checkitemIds);
}

2.2.3 服務實現類

在health_service_provider工程中創建CheckGroupServiceImpl實現類

package com.itheima.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 檢查組服務
 */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    //添加檢查組合,同時需要設置檢查組合和檢查項的關聯關系
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }
  	//設置檢查組合和檢查項的關聯關系
    public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds){
          if(checkitemIds != null && checkitemIds.length > 0){
              for (Integer checkitemId : checkitemIds) {
                  Map<String,Integer> map = new HashMap<>();
                  map.put("checkgroup_id",checkGroupId);
                  map.put("checkitem_id",checkitemId);
                  checkGroupDao.setCheckGroupAndCheckItem(map);
              }
          }
      }
}

2.2.4 Dao接口

創建CheckGroupDao接口

package com.itheima.dao;
import com.github.pagehelper.Page;
import com.itheima.pojo.CheckGroup;
import java.util.List;
import java.util.Map;
/**
 * 持久層Dao接口
 */
public interface CheckGroupDao {
    void add(CheckGroup checkGroup);
    void setCheckGroupAndCheckItem(Map map);
}

2.2.5 Mapper映射文件

創建CheckGroupDao.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.itheima.dao.CheckGroupDao">
    <!--新增-->
    <insert id="add" parameterType="com.itheima.pojo.CheckGroup">
        <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_checkgroup(code,name,sex,helpCode,remark,attention)
            values 
      	(#{code},#{name},#{sex},#{helpCode},#{remark},#{attention})
    </insert>
	<!--設置檢查組和檢查項的關聯關系-->
    <insert id="setCheckGroupAndCheckItem" parameterType="hashmap">
        insert into t_checkgroup_checkitem(checkgroup_id,checkitem_id) 
      		values
      	(#{checkgroup_id},#{checkitem_id})
    </insert>
</mapper>

3. 檢查組分頁

3.1 完善頁面

3.1.1 定義分頁相關模型數據

pagination: {//分頁相關模型數據
  currentPage: 1,//當前頁碼
  pageSize:10,//每頁顯示的記錄數
  total:0,//總記錄數
  queryString:null//查詢條件
},
dataList: [],//當前頁要展示的分頁列表數據

3.1.2 定義分頁方法

在頁面中提供了findPage方法用於分頁查詢,為了能夠在checkgroup.html頁面加載后直接可以展示分頁數據,可以在VUE提供的鈎子函數created中調用findPage方法

//鈎子函數,VUE對象初始化完成后自動執行
created() {
  this.findPage();
}
//分頁查詢
findPage() {
  //分頁參數
  var param = {
    currentPage:this.pagination.currentPage,//頁碼
    pageSize:this.pagination.pageSize,//每頁顯示的記錄數
    queryString:this.pagination.queryString//查詢條件
  };
  //請求后台
  axios.post("/checkgroup/findPage.do",param).then((response)=> {
    //為模型數據賦值,基於VUE的雙向綁定展示到頁面
    this.dataList = response.data.rows;
    this.pagination.total = response.data.total;
  });
}

3.1.3 完善分頁方法執行時機

除了在created鈎子函數中調用findPage方法查詢分頁數據之外,當用戶點擊查詢按鈕或者點擊分頁條中的頁碼時也需要調用findPage方法重新發起查詢請求。

為查詢按鈕綁定單擊事件,調用findPage方法

<el-button @click="findPage()" class="dalfBut">查詢</el-button>

為分頁條組件綁定current-change事件,此事件是分頁條組件自己定義的事件,當頁碼改變時觸發,對應的處理函數為handleCurrentChange

<el-pagination
               class="pagiantion"
               @current-change="handleCurrentChange"
               :current-page="pagination.currentPage"
               :page-size="pagination.pageSize"
               layout="total, prev, pager, next, jumper"
               :total="pagination.total">
</el-pagination>

定義handleCurrentChange方法

//切換頁碼handleCurrentChange(currentPage) {
  //currentPage為切換后的頁碼
  this.pagination.currentPage = currentPage;
  this.findPage();
}

3.2 后台代碼

3.2.1 Controller

在CheckGroupController中增加分頁查詢方法

//分頁查詢
@RequestMapping("/findPage")
public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
  PageResult pageResult = checkGroupService.pageQuery(
    queryPageBean.getCurrentPage(), 
    queryPageBean.getPageSize(), 
    queryPageBean.getQueryString()
  );
  return pageResult;
}

3.2.2 服務接口

在CheckGroupService服務接口中擴展分頁查詢方法

public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString);

3.2.3 服務實現類

在CheckGroupServiceImpl服務實現類中實現分頁查詢方法,基於Mybatis分頁助手插件實現分頁

public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
  PageHelper.startPage(currentPage,pageSize);
  Page<CheckItem> page = checkGroupDao.selectByCondition(queryString);
  return new PageResult(page.getTotal(),page.getResult());
}

3.2.4 Dao接口

在CheckGroupDao接口中擴展分頁查詢方法

public Page<CheckGroup> selectByCondition(String queryString);

3.2.5 Mapper映射文件

在CheckGroupDao.xml文件中增加SQL定義

<select id="selectByCondition" parameterType="string" resultType="com.itheima.pojo.CheckGroup">
  select * from t_checkgroup
  <if test="value != null and value.length > 0">
    where code = #{value} or name = #{value} or helpCode = #{value}
  </if>
</select>

4. 編輯檢查組

4.1 完善頁面

用戶點擊編輯按鈕時,需要彈出編輯窗口並且將當前記錄的數據進行回顯,用戶修改完成后點擊確定按鈕將修改后的數據提交到后台進行數據庫操作。此處進行數據回顯的時候,除了需要檢查組基本信息的回顯之外,還需要回顯當前檢查組包含的檢查項(以復選框勾選的形式回顯)。

4.1.1 綁定單擊事件

需要為編輯按鈕綁定單擊事件,並且將當前行數據作為參數傳遞給處理函數

<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">編輯</el-button>
handleUpdate(row) {
  alert(row);
}

4.1.2 彈出編輯窗口回顯數據

當前頁面的編輯窗口已經提供好了,默認處於隱藏狀態。在handleUpdate方法中需要將編輯窗口展示出來,並且需要發送多個ajax請求分別查詢當前檢查組數據、所有檢查項數據、當前檢查組包含的檢查項id用於基本數據回顯

handleUpdate(row) {
  //發送ajax請求根據id查詢檢查組信息,用於基本信息回顯
  axios.get("/checkgroup/findById.do?id=" + row.id).then((res)=>{
    if(res.data.flag){
      //彈出編輯窗口
      this.dialogFormVisible4Edit = true;
      //默認選中第一個標簽頁
      this.activeName='first';
      //為模型數據賦值,通過VUE數據雙向綁定進行信息的回顯
      this.formData = res.data.data;
      //發送ajax請求查詢所有的檢查項信息,用於檢查項表格展示
      axios.get("/checkitem/findAll.do").then((res)=> {
        if(res.data.flag){
          //為模型數據賦值,通過VUE數據雙向綁定進行信息的回顯
          this.tableData = res.data.data;
          //查詢當前檢查組包含的所有檢查項id,用於頁面回顯
          axios.get("/checkgroup/findCheckItemIdsByCheckGroupId.do?id=" + row.id).then((res)=> {
            //為模型數據賦值,通過VUE數據雙向綁定進行信息的回顯
            if(res.data.flag){
                this.checkitemIds = res.data.data;
            }else{
                this.$message.error(res.data.message);
            }
          });
        }else{
          this.$message.error(res.data.message);
        }
      });
    }else{
      this.$message.error("獲取數據失敗,請刷新當前頁面");
    }
  });
}

4.1.3 發送請求

在編輯窗口中修改完成后,點擊確定按鈕需要提交請求,所以需要為確定按鈕綁定事件並提供處理函數handleEdit

<el-button type="primary" @click="handleEdit()">確定</el-button>
//編輯
handleEdit() {
  //發送ajax請求,提交模型數據
  axios.post("/checkgroup/edit.do?checkitemIds="+this.checkitemIds,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();
  });
}

4.2 后台代碼

4.2.1 Controller

在CheckGroupController中增加方法

//根據id查詢
@RequestMapping("/findById")
public Result findById(Integer id){
  CheckGroup checkGroup = checkGroupService.findById(id);
  if(checkGroup != null){
    Result result = new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS);
    result.setData(checkGroup);
    return result;
  }
  return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
}

//根據檢查組合id查詢對應的所有檢查項id
@RequestMapping("/findCheckItemIdsByCheckGroupId")
public Result findCheckItemIdsByCheckGroupId(Integer id){
    try{
        List<Integer> checkitemIds = 
            checkGroupService.findCheckItemIdsByCheckGroupId(id);
        return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,checkitemIds);
    }catch (Exception e){
        e.printStackTrace();
        return new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL);
    }
}

//編輯
@RequestMapping("/edit")
public Result edit(@RequestBody CheckGroup checkGroup,Integer[] checkitemIds){
  try {
    checkGroupService.edit(checkGroup,checkitemIds);
  }catch (Exception e){
    return new Result(false,MessageConstant.EDIT_CHECKGROUP_FAIL);
  }
  return new Result(true,MessageConstant.EDIT_CHECKGROUP_SUCCESS);
}

4.2.2 服務接口

在CheckGroupService服務接口中擴展方法

CheckGroup findById(Integer id);
List<Integer> findCheckItemIdsByCheckGroupId(Integer id);
public void edit(CheckGroup checkGroup,Integer[] checkitemIds);

4.2.3 服務實現類

在CheckGroupServiceImpl實現類中實現編輯方法

public CheckGroup findById(Integer id) {
  return checkGroupDao.findById(id);
}

public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
  return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
}

//編輯檢查組,同時需要更新和檢查項的關聯關系
public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
  //根據檢查組id刪除中間表數據(清理原有關聯關系)
  checkGroupDao.deleteAssociation(checkGroup.getId());
  //向中間表(t_checkgroup_checkitem)插入數據(建立檢查組和檢查項關聯關系)
  setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
  //更新檢查組基本信息
  checkGroupDao.edit(checkGroup);
}

//向中間表(t_checkgroup_checkitem)插入數據(建立檢查組和檢查項關聯關系)
public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds){
  if(checkitemIds != null && checkitemIds.length > 0){
    for (Integer checkitemId : checkitemIds) {
      Map<String,Integer> map = new HashMap<>();
      map.put("checkgroup_id",checkGroupId);
      map.put("checkitem_id",checkitemId);
      checkGroupDao.setCheckGroupAndCheckItem(map);
    }
  }
}

4.2.4 Dao接口

在CheckGroupDao接口中擴展方法

CheckGroup findById(Integer id);
List<Integer> findCheckItemIdsByCheckGroupId(Integer id);
void setCheckGroupAndCheckItem(Map map);
void deleteAssociation(Integer id);
void edit(CheckGroup checkGroup);

4.2.5 Mapper映射文件

在CheckGroupDao.xml中擴展SQL語句

<select id="findById" parameterType="int" resultType="com.itheima.pojo.CheckGroup">
  select * from t_checkgroup where id = #{id}
</select>
<select id="findCheckItemIdsByCheckGroupId" parameterType="int" resultType="int">
  select checkitem_id from t_checkgroup_checkitem where checkgroup_id = #{id}
</select>
<!--向中間表插入數據(建立檢查組和檢查項關聯關系)-->
<insert id="setCheckGroupAndCheckItem" parameterType="hashmap">
  insert into t_checkgroup_checkitem(checkgroup_id,checkitem_id) 
  	values
  (#{checkgroup_id},#{checkitem_id})
</insert>
<!--根據檢查組id刪除中間表數據(清理原有關聯關系)-->
<delete id="deleteAssociation" parameterType="int">
  delete from t_checkgroup_checkitem where checkgroup_id = #{id}
</delete>
<!--編輯-->
<update id="edit" parameterType="com.itheima.pojo.CheckGroup">
  update t_checkgroup
  <set>
    <if test="name != null">
      name = #{name},
    </if>
    <if test="sex != null">
      sex = #{sex},
    </if>
    <if test="code != null">
      code = #{code},
    </if>
    <if test="helpCode != null">
      helpCode = #{helpCode},
    </if>
    <if test="attention != null">
      attention = #{attention},
    </if>
    <if test="remark != null">
      remark = #{remark},
    </if>
  </set>
  where id = #{id}
</update>

視頻地址:https://www.bilibili.com/video/BV1Bo4y117zV


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM