尚医通02:医院API的CRUD+环境搭建

目录

今日必会

项目环境搭建

医院设置模块搭建

配置使用Swagger2

统一返回结果

实现带条件带分页查询接口

新增、修改接口开发

批量删除、锁定医院设置

统一异常处理


今日必会

1.简单的搭建环境。要明白什么时候是pom/war/jar

        yygh_parent         

        common               

        model                    无                                 

        service                 


2.各个模块的作用

    common:工具类,所有的模块都要依赖他。

    common_utils:用于返回结果的封装。

    service_utils:用于swagger的配置,还配置了统一处理异常,所以引入了common_utils

    model :实体类

    service:api接口服务

    service_hosp:医院api接口

      1. config:配置类,他是mapper的配置类说白了就是dao层配置(数据库和后台)里面有分页插件。

      2.controller:这是前台地址第一次到达的地方,处理HTTP请求,并将请求的数据传递给其他层进行处理。里面有CRUD。

      3.mapper:Mapper层负责处理数据的持久化和访问。

      4. service:本层起到了连接Controller层和Mapper层的桥梁作用,负责实现业务逻和数据操作的协调,是实现系统功能的关键部分。


 3.了解每个接口的参数和返回值

   ※新增:参数:hospitalset    返回值:R.ok()

   ※修改:要先进行数据回显,

      根据id查询信息, 参数:id 返回值:R(HospitalSet)

      然后修改医院设置(保存接口) 参数: HospitalSet  返回值:R.ok()


  ※批量删除 参数:listidlis   返回值:R.ok()

  ※锁定医院  参数:id ,status     返回值:R.ok()


4.了解分页的逻辑

5.了解get/post/delete mapping

以下代码必须全会敲

//医院设置接口
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
public class HospitalSetController {
    @Autowired
    private HospitalSetService hospitalSetService;

    //chaxun
    //查询所有医院设置
    //查询所有医院设置
    @ApiOperation(value = "医院设置列表")
    @GetMapping("findAll")
    public R findAll() {
        List list = hospitalSetService.list();
        return R.ok().data("list",list);
    }

    @ApiOperation(value = "医院设置删除")
    @DeleteMapping("{id}")
    public R removeById(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id){
        hospitalSetService.removeById(id);
        return R.ok();
    }

 @ApiOperation(value="分页查询")
    @GetMapping("pageQuery/{page}/{limit}")
    public R  pageQuery(@PathVariable Long page,@PathVariable Long limit){

        //1.封装分页参数
     Page pageparm = new Page<>(page,limit);
       //2.实现分页查询
      hospitalSetService.page(pageparm);
      //3.取出结果
      List recods = pageparm.getRecords();
      Long total = pageparm.getTotal();
      //4.封装返回
      return R.ok().data("recods",recods).data("total",total);
 }

    @ApiOperation(value="分页查询加条件")
    @GetMapping("pageQuer/{page}/{limit}")
    public R  pagelist(@PathVariable Long page, @PathVariable Long limit, @RequestBody HospitalSetQueryVo hospitalSetQueryVo){
      //1.
        String hosname = hospitalSetQueryVo.getHosname();
        String hoscode = hospitalSetQueryVo.getHoscode();
        QueryWrapper wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(hosname)){

            wrapper.like("hosname",hosname);


        }
        if (!StringUtils.isEmpty(hoscode)){

            wrapper.eq("hoscode",hoscode);

        }
        //1.封装分页参数
        Page pageparm = new Page<>(page,limit);
        //2.实现分页查询
        hospitalSetService.page(pageparm,wrapper);
        //3.取出结果
        List recods = pageparm.getRecords();
        Long total = pageparm.getTotal();
        //4.封装返回
        return R.ok().data("records",recods).data("total",total);
    }

    @ApiOperation(value = "新增医院设置")
    @PostMapping("save")
    public R save(@RequestBody HospitalSet hospitalSet){
        boolean save = hospitalSetService.save(hospitalSet);
        if(save){
            return R.ok();
        }else {
            return R.error();
        }
    }

// 新增加 新加
    @ApiOperation(value = "根据id查询信息")
    @GetMapping("getById/{id}")
    public R getById(@PathVariable Long id){
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        return R.ok().data("hospitalSet",hospitalSet);
    }
//修改医院设置

    @ApiOperation(value = "修改医院设置")
    @PostMapping("update")
    public R update(@RequestBody HospitalSet hospitalSet)
    {
        boolean update = hospitalSetService.updateById(hospitalSet);
        if(update){
            return R.ok();
        }else {
            return R.error();
        }
    }
// 1.
    @ApiOperation(value = "根据id集合批量删除")
    @DeleteMapping("delByIds")
    public R delByIds(@RequestBody  List idList){
        boolean remove = hospitalSetService.removeByIds(idList);
        if(remove){
            return R.ok();
        }else {
            return R.error();
        }
    }


//2.
@ApiOperation(value = "医院设置锁定和解锁")
@PutMapping("lockHospitalSet/{id}/{status}")
public R lockHospitalSet(@PathVariable Long id,
                         @PathVariable Integer status) {
    //1根据id查询数据
    HospitalSet hospitalSet = hospitalSetService.getById(id);
    //2修改数据
    hospitalSet.setStatus(status);
    hospitalSetService.updateById(hospitalSet);
    return R.ok();
}

项目环境搭建

1、项目开发方式

前后端分离

尚医通02:医院API的CRUD+环境搭建_第1张图片

2、后端工程分层

(1)分类

*jar:java工程

*war:web工程

*pom:父工程

(2)分层

尚医通02:医院API的CRUD+环境搭建_第2张图片


3、数据库搭建

(1)建库建表脚本

# Host: localhost  (Version 5.7.19-log)
# Date: 2020-07-31 12:02:29
# Generator: MySQL-Front 6.1  (Build 1.26)


#
# Database "yygh_cmn"
#

CREATE DATABASE IF NOT EXISTS `yygh_cmn` CHARACTER SET utf8;
USE `yygh_cmn`;

#
# Structure for table "dict"
#

CREATE TABLE `dict` (
  `id` bigint(20) NOT NULL DEFAULT '0' COMMENT 'id',
  `parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '上级id',
  `name` varchar(100) NOT NULL DEFAULT '' COMMENT '名称',
  `value` bigint(20) DEFAULT NULL COMMENT '值',
  `dict_code` varchar(20) DEFAULT NULL COMMENT '编码',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '1' COMMENT '删除标记(0:不可用 1:可用)',
  PRIMARY KEY (`id`),
  KEY `idx_dict_code` (`dict_code`),
  KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='组织架构表';

#
# Database "yygh_hosp"
#

CREATE DATABASE IF NOT EXISTS `yygh_hosp` CHARACTER SET utf8mb4;
USE `yygh_hosp`;

#
# Structure for table "hospital_set"
#

CREATE TABLE `hospital_set` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `hosname` varchar(100) DEFAULT NULL COMMENT '医院名称',
  `hoscode` varchar(30) DEFAULT NULL COMMENT '医院编号',
  `api_url` varchar(100) DEFAULT NULL COMMENT 'api基础路径',
  `sign_key` varchar(50) DEFAULT NULL COMMENT '签名秘钥',
  `contacts_name` varchar(20) DEFAULT NULL COMMENT '联系人',
  `contacts_phone` varchar(11) DEFAULT NULL COMMENT '联系人手机',
  `status` tinyint(3) NOT NULL DEFAULT '0' COMMENT '状态',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_hoscode` (`hoscode`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='医院设置表';

#
# Database "yygh_order"
#

CREATE DATABASE IF NOT EXISTS `yygh_order` CHARACTER SET utf8;
USE `yygh_order`;

#
# Structure for table "order_info"
#

CREATE TABLE `order_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_id` bigint(20) DEFAULT NULL,
  `out_trade_no` varchar(300) DEFAULT NULL COMMENT '订单交易号',
  `hoscode` varchar(30) DEFAULT NULL COMMENT '医院编号',
  `hosname` varchar(100) DEFAULT NULL COMMENT '医院名称',
  `depcode` varchar(30) DEFAULT NULL COMMENT '科室编号',
  `depname` varchar(20) DEFAULT NULL COMMENT '科室名称',
  `title` varchar(20) DEFAULT NULL COMMENT '医生职称',
  `hos_schedule_id` varchar(50) DEFAULT NULL COMMENT '排班编号(医院自己的排班主键)',
  `reserve_date` date DEFAULT NULL COMMENT '安排日期',
  `reserve_time` tinyint(3) DEFAULT '0' COMMENT '安排时间(0:上午 1:下午)',
  `patient_id` bigint(20) DEFAULT NULL COMMENT '就诊人id',
  `patient_name` varchar(20) DEFAULT NULL COMMENT '就诊人名称',
  `patient_phone` varchar(11) DEFAULT NULL COMMENT '就诊人手机',
  `hos_record_id` varchar(30) DEFAULT NULL COMMENT '预约记录唯一标识(医院预约记录主键)',
  `number` int(11) DEFAULT NULL COMMENT '预约号序',
  `fetch_time` varchar(50) DEFAULT NULL COMMENT '建议取号时间',
  `fetch_address` varchar(255) DEFAULT NULL COMMENT '取号地点',
  `amount` decimal(10,0) DEFAULT NULL COMMENT '医事服务费',
  `quit_time` datetime DEFAULT NULL COMMENT '退号时间',
  `order_status` tinyint(3) DEFAULT NULL COMMENT '订单状态',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_out_trade_no` (`out_trade_no`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_hoscode` (`hoscode`),
  KEY `idx_hos_schedule_id` (`hos_schedule_id`),
  KEY `idx_hos_record_id` (`hos_record_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='订单表';

#
# Structure for table "payment_info"
#

CREATE TABLE `payment_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `out_trade_no` varchar(30) DEFAULT NULL COMMENT '对外业务编号',
  `order_id` bigint(20) DEFAULT NULL COMMENT '订单id',
  `payment_type` tinyint(1) DEFAULT NULL COMMENT '支付类型(微信 支付宝)',
  `trade_no` varchar(50) DEFAULT NULL COMMENT '交易编号',
  `total_amount` decimal(10,2) DEFAULT NULL COMMENT '支付金额',
  `subject` varchar(200) DEFAULT NULL COMMENT '交易内容',
  `payment_status` tinyint(3) DEFAULT NULL COMMENT '支付状态',
  `callback_time` datetime DEFAULT NULL COMMENT '回调时间',
  `callback_content` varchar(1000) DEFAULT NULL COMMENT '回调信息',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  KEY `idx_out_trade_no` (`out_trade_no`),
  KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COMMENT='支付信息表';

#
# Structure for table "refund_info"
#

CREATE TABLE `refund_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `out_trade_no` varchar(50) DEFAULT NULL COMMENT '对外业务编号',
  `order_id` bigint(20) DEFAULT NULL COMMENT '订单编号',
  `payment_type` tinyint(3) DEFAULT NULL COMMENT '支付类型(微信 支付宝)',
  `trade_no` varchar(50) DEFAULT NULL COMMENT '交易编号',
  `total_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
  `subject` varchar(200) DEFAULT NULL COMMENT '交易内容',
  `refund_status` tinyint(3) DEFAULT NULL COMMENT '退款状态',
  `callback_content` varchar(1000) DEFAULT NULL COMMENT '回调信息',
  `callback_time` datetime DEFAULT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  KEY `idx_out_trade_no` (`out_trade_no`),
  KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='退款信息表';

#
# Database "yygh_user"
#

CREATE DATABASE IF NOT EXISTS `yygh_user` CHARACTER SET utf8;
USE `yygh_user`;

#
# Structure for table "patient"
#

CREATE TABLE `patient` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `certificates_type` varchar(3) DEFAULT NULL COMMENT '证件类型',
  `certificates_no` varchar(30) DEFAULT NULL COMMENT '证件编号',
  `sex` tinyint(3) DEFAULT NULL COMMENT '性别',
  `birthdate` date DEFAULT NULL COMMENT '出生年月',
  `phone` varchar(11) DEFAULT NULL COMMENT '手机',
  `is_marry` tinyint(3) DEFAULT NULL COMMENT '是否结婚',
  `province_code` varchar(20) DEFAULT NULL COMMENT '省code',
  `city_code` varchar(20) DEFAULT NULL COMMENT '市code',
  `district_code` varchar(20) DEFAULT NULL COMMENT '区code',
  `address` varchar(100) DEFAULT NULL COMMENT '详情地址',
  `contacts_name` varchar(20) DEFAULT NULL COMMENT '联系人姓名',
  `contacts_certificates_type` varchar(3) DEFAULT NULL COMMENT '联系人证件类型',
  `contacts_certificates_no` varchar(30) DEFAULT NULL COMMENT '联系人证件号',
  `contacts_phone` varchar(11) DEFAULT NULL COMMENT '联系人手机',
  `card_no` varchar(50) DEFAULT NULL COMMENT '就诊卡号',
  `is_insure` tinyint(3) DEFAULT '0' COMMENT '是否有医保',
  `status` tinyint(3) NOT NULL DEFAULT '0' COMMENT '状态(0:默认 1:已认证)',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='就诊人表';

#
# Structure for table "user_info"
#

CREATE TABLE `user_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `openid` varchar(100) DEFAULT NULL COMMENT '微信openid',
  `nick_name` varchar(20) DEFAULT NULL COMMENT '昵称',
  `phone` varchar(11) NOT NULL DEFAULT '' COMMENT '手机号',
  `name` varchar(20) DEFAULT NULL COMMENT '用户姓名',
  `certificates_type` varchar(3) DEFAULT NULL COMMENT '证件类型',
  `certificates_no` varchar(30) DEFAULT NULL COMMENT '证件编号',
  `certificates_url` varchar(200) DEFAULT NULL COMMENT '证件路径',
  `auth_status` tinyint(3) NOT NULL DEFAULT '0' COMMENT '认证状态(0:未认证 1:认证中 2:认证成功 -1:认证失败)',
  `status` tinyint(3) NOT NULL DEFAULT '1' COMMENT '状态(0:锁定 1:正常)',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  KEY `uk_mobile` (`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='用户表';

#
# Structure for table "user_login_record"
#

CREATE TABLE `user_login_record` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
  `ip` varchar(32) DEFAULT NULL COMMENT 'ip',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除(1:已删除,0:未删除)',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8 COMMENT='用户登录记录表';

尚医通02:医院API的CRUD+环境搭建_第3张图片

尚医通02:医院API的CRUD+环境搭建_第4张图片


(2)数据库设计规范

*公司有规范,遵循公司规范

*公司没有规范,遵循行业规范《阿里巴巴Java开发手册


3、工程结构介绍

尚医通02:医院API的CRUD+环境搭建_第5张图片


4、创建父工程

(1)创建springboot工程yygh_parent

尚医通02:医院API的CRUD+环境搭建_第6张图片

(2)修改pom.xml

尚医通02:医院API的CRUD+环境搭建_第7张图片

xml version="1.0" encoding="UTF-8"?>

  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0modelVersion>

  

    <parent>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-parentartifactId>

        <version>2.2.1.RELEASEversion>

        <relativePath/> 

    parent>

    <groupId>com.atguigugroupId>

    <artifactId>yygh_parentartifactId>

    <packaging>pompackaging>

    <version>0.0.1-SNAPSHOTversion>

    <name>yygh_parentname>

    <description>Demo project for Spring Bootdescription>

    <properties>

        <java.version>1.8java.version>

        <cloud.version>Hoxton.RELEASEcloud.version>

        <alibaba.version>2.2.0.RELEASEalibaba.version>

        <mybatis-plus.version>3.3.1mybatis-plus.version>

        <mysql.version>5.1.46mysql.version>

        <swagger.version>2.7.0swagger.version>

        <jwt.version>0.7.0jwt.version>

        <fastjson.version>1.2.29fastjson.version>

        <httpclient.version>4.5.1httpclient.version>

        <easyexcel.version>2.2.0-beta2easyexcel.version>

        <aliyun.version>4.1.1aliyun.version>

        <oss.version>3.9.1oss.version>

        <jodatime.version>2.10.1jodatime.version>

    properties>

  

    

    <dependencyManagement>

        <dependencies>

            <dependency>

                <groupId>org.springframework.cloudgroupId>

                <artifactId>spring-cloud-dependenciesartifactId>

                <version>${cloud.version}version>

                <type>pomtype>

                <scope>importscope>

            dependency>

  

            <dependency>

                <groupId>com.alibaba.cloudgroupId>

                <artifactId>spring-cloud-alibaba-dependenciesartifactId>

                <version>${alibaba.version}version>

                <type>pomtype>

                <scope>importscope>

            dependency>

  

            

            <dependency>

                <groupId>com.baomidougroupId>

                <artifactId>mybatis-plus-boot-starterartifactId>

                <version>${mybatis-plus.version}version>

            dependency>

  

            <dependency>

                <groupId>mysqlgroupId>

                <artifactId>mysql-connector-javaartifactId>

                <version>${mysql.version}version>

            dependency>

  

            

            <dependency>

                <groupId>io.springfoxgroupId>

                <artifactId>springfox-swagger2artifactId>

                <version>${swagger.version}version>

            dependency>

            

            <dependency>

                <groupId>io.springfoxgroupId>

                <artifactId>springfox-swagger-uiartifactId>

                <version>${swagger.version}version>

            dependency>

  

            <dependency>

                <groupId>io.jsonwebtokengroupId>

                <artifactId>jjwtartifactId>

                <version>${jwt.version}version>

            dependency>

  

            <dependency>

                <groupId>org.apache.httpcomponentsgroupId>

                <artifactId>httpclientartifactId>

                <version>${httpclient.version}version>

            dependency>

  

            <dependency>

                <groupId>com.alibabagroupId>

                <artifactId>fastjsonartifactId>

                <version>${fastjson.version}version>

            dependency>

  

            <dependency>

                <groupId>com.alibabagroupId>

                <artifactId>easyexcelartifactId>

                <version>${easyexcel.version}version>

            dependency>

  

            <dependency>

                <groupId>com.aliyungroupId>

                <artifactId>aliyun-java-sdk-coreartifactId>

                <version>${aliyun.version}version>

            dependency>

  

            <dependency>

                <groupId>com.aliyun.ossgroupId>

                <artifactId>aliyun-sdk-ossartifactId>

                <version>${oss.version}version>

            dependency>

  

            

            <dependency>

                <groupId>joda-timegroupId>

                <artifactId>joda-timeartifactId>

                <version>${jodatime.version}version>

            dependency>

        dependencies>

    dependencyManagement>

  

    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.bootgroupId>

                <artifactId>spring-boot-maven-pluginartifactId>

            plugin>

        plugins>

    build>

  

  project>



  

    4.0.0

  

    

        org.springframework.boot

        spring-boot-starter-parent

        2.2.1.RELEASE

         

    

    com.atguigu

    yygh_parent

    pom

    0.0.1-SNAPSHOT

    yygh_parent

    Demo project for Spring Boot

    

        1.8

        Hoxton.RELEASE

        2.2.0.RELEASE

        3.3.1

        5.1.46

        2.7.0

        0.7.0

        1.2.29

        4.5.1

        2.2.0-beta2

        4.1.1

        3.9.1

        2.10.1

    

  

    

    

        

            

                org.springframework.cloud

                spring-cloud-dependencies

                ${cloud.version}

                pom

                import

            

  

            

                com.alibaba.cloud

                spring-cloud-alibaba-dependencies

                ${alibaba.version}

                pom

                import

            

  

            

            

                com.baomidou

                mybatis-plus-boot-starter

                ${mybatis-plus.version}

            

  

            

                mysql

                mysql-connector-java

                ${mysql.version}

            

  

            

            

                io.springfox

                springfox-swagger2

                ${swagger.version}

            

            

            

                io.springfox

                springfox-swagger-ui

                ${swagger.version}

            

  

            

                io.jsonwebtoken

                jjwt

                ${jwt.version}

            

  

            

                org.apache.httpcomponents

                httpclient

                ${httpclient.version}

            

  

            

                com.alibaba

                fastjson

                ${fastjson.version}

            

  

            

                com.alibaba

                easyexcel

                ${easyexcel.version}

            

  

            

                com.aliyun

                aliyun-java-sdk-core

                ${aliyun.version}

            

  

            

                com.aliyun.oss

                aliyun-sdk-oss

                ${oss.version}

            

  

            

            

                joda-time

                joda-time

                ${jodatime.version}

            

        

    

  

    

        

            

                org.springframework.boot

                spring-boot-maven-plugin

            

        

    

  

  

(3)删除src

尚医通02:医院API的CRUD+环境搭建_第8张图片

5、搭建model模块

(1)在父工程yygh_parent下面创建模块model

尚医通02:医院API的CRUD+环境搭建_第9张图片

(2)添加项目需要的依赖

<dependencies>

    <dependency>

        <groupId>org.projectlombokgroupId>

        <artifactId>lombokartifactId>

    dependency>

    

    <dependency>

        <groupId>com.baomidougroupId>

        <artifactId>mybatis-plus-boot-starterartifactId>

        <scope>provided scope>

    dependency>

    

    <dependency>

        <groupId>io.springfoxgroupId>

        <artifactId>springfox-swagger2artifactId>

        <scope>provided scope>

    dependency>

    <dependency>

        <groupId>com.alibabagroupId>

        <artifactId>easyexcelartifactId>

        <scope>provided scope>

    dependency>

    <dependency>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-data-mongodbartifactId>

        <scope>provided scope>

    dependency>

    <dependency>

        <groupId>com.alibabagroupId>

        <artifactId>fastjsonartifactId>

        <scope>provided scope>

    dependency>

  dependencies>

(3)复制项目实体类和VO类

尚医通02:医院API的CRUD+环境搭建_第10张图片

尚医通02:医院API的CRUD+环境搭建_第11张图片

6、搭建service模块

(1)在父工程yygh_parent下面创建模块service

尚医通02:医院API的CRUD+环境搭建_第12张图片

(2)修改pom、添加通用依赖

尚医通02:医院API的CRUD+环境搭建_第13张图片

<dependencies>

    <dependency>

        <groupId>com.atguigugroupId>

        <artifactId>modelartifactId>

        <version>0.0.1-SNAPSHOTversion>

    dependency>

    

    <dependency>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-webartifactId>

    dependency>

    

    <dependency>

        <groupId>com.baomidougroupId>

        <artifactId>mybatis-plus-boot-starterartifactId>

    dependency>

    

    <dependency>

        <groupId>mysqlgroupId>

        <artifactId>mysql-connector-javaartifactId>

    dependency>

    

    <dependency>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-devtoolsartifactId>

        <optional>trueoptional>

    dependency>

    

    

  dependencies>

(3)删除src


尚医通02:医院API的CRUD+环境搭建_第14张图片

7、搭建医院模块service_hosp模块


(1)在父模块·service模块下面创建子模块service_hosp

尚医通02:医院API的CRUD+环境搭建_第15张图片

尚医通02:医院API的CRUD+环境搭建_第16张图片

医院设置模块搭建
  1. 确认需求

医院设置主要是用来保存开通医院的一些基本信息,每个医院一条信息,保存了医院编号(平台分配,全局唯一)和接口调用相关的签名key等信息,是整个流程的第一步,只有开通了医院设置信息,才可以上传医院相关信息。我们所开发的功能就是基于单表的一个CRUD、锁定/解锁和发送签名信息这些基本功能。


2、改造service_hosp模块

(1)resources目录下创建文件 application.properties


# 服务端口

  server.port=8201

  # 服务名

  spring.application.name=service-hosp

  

  # 环境设置:devtestprod

  spring.profiles.active=dev

  

  # mysql数据库连接

  spring.datasource.driver-class-name=com.mysql.jdbc.Driver

  spring.datasource.url=jdbc:mysql://localhost:3306/yygh_hosp?characterEncoding=utf-8&useSSL=false

  spring.datasource.username=root

  spring.datasource.password=123123

  

  #返回json的全局时间格式

  spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

  spring.jackson.time-zone=GMT+8

  

  #mybatis日志

  mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(2)创建主目录、启动类

尚医通02:医院API的CRUD+环境搭建_第17张图片


@SpringBootApplication

  public class ServiceHospApplication {

    public static void main(String[] args) {

        SpringApplication.run(ServiceHospApplication.class,args);

    }

  }

3、搭建MP框架

(1)确认实体

尚医通02:医院API的CRUD+环境搭建_第18张图片

(2)搭建mapper

尚医通02:医院API的CRUD+环境搭建_第19张图片  


public interface HospitalSetMapper extends BaseMapper<HospitalSet> {

}

(3)搭建service

尚医通02:医院API的CRUD+环境搭建_第20张图片

public interface HospitalSetService extends IService<HospitalSet> {

}

@Service

  public class HospitalSetServiceImpl

        extends ServiceImpl<HospitalSetMapper, HospitalSet>

        implements HospitalSetService {

}

(4)搭建controller

//医院设置接口

  @RestController

@RequestMapping("/admin/hosp/hospitalSet")

  public class HospitalSetController {

  

    @Autowired

    private HospitalSetService hospitalSetService;

  

    @GetMapping("findAll")

    public List<HospitalSet> findAll(){

        List<HospitalSet> list = hospitalSetService.list();

        return list;

    }

  

  }

(5)创建配置类

@Configuration

@EnableTransactionManagement

@MapperScan("com.atguigu.yygh.hosp.mapper")

  public class HospConfig {

}

(6)启动测试

尚医通02:医院API的CRUD+环境搭建_第21张图片


(7)实现删除

尚医通02:医院API的CRUD+环境搭建_第22张图片

@DeleteMapping("{id}")

  public boolean delHospset(@PathVariable Long id){

    boolean remove = hospitalSetService.removeById(id);

    return remove;

  }

配置使用Swagger2

1、是什么

前后端分离开发模式中,api文档是最好的沟通方式。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

Swagger根据代码生成web版api文档


2、为什么

及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)

规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)

一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)

可测性 (直接在接口文档上进行测试,以方便理解业务)

3、整合框架

(1)在yygh_parent下创建模块common父模块

尚医通02:医院API的CRUD+环境搭建_第23张图片

(2)修改pom,引入依赖

尚医通02:医院API的CRUD+环境搭建_第24张图片


<dependencies>

    <dependency>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-webartifactId>

        <scope>provided scope>

    dependency>

  

    

    <dependency>

        <groupId>com.baomidougroupId>

        <artifactId>mybatis-plus-boot-starterartifactId>

        <scope>provided scope>

    dependency>

  

    

    <dependency>

        <groupId>org.projectlombokgroupId>

        <artifactId>lombokartifactId>

    dependency>

  

    

    <dependency>

        <groupId>io.springfoxgroupId>

        <artifactId>springfox-swagger2artifactId>

    dependency>

    <dependency>

        <groupId>io.springfoxgroupId>

        <artifactId>springfox-swagger-uiartifactId>

    dependency>

  

    <dependency>

        <groupId>com.alibabagroupId>

        <artifactId>fastjsonartifactId>

    dependency>

  dependencies>

(3)删除src

(4)在common下面创建子模块service_utils

尚医通02:医院API的CRUD+环境搭建_第25张图片

(5)创建包com.atguigu.yygh.common.config,创建类Swagger2Config

尚医通02:医院API的CRUD+环境搭建_第26张图片


@Configuration

@EnableSwagger2

  public class Swagger2Config {

  

    @Bean

    public Docket webApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)

                .groupName("webApi")

                .apiInfo(webApiInfo())

                .select()

                //只显示api路径下的页面

                //.paths(Predicates.and(PathSelectors.regex("/api/.*")))

                .build();

    }

  

    @Bean

    public Docket adminApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)

                .groupName("adminApi")

                .apiInfo(adminApiInfo())

                .select()

                //只显示admin路径下的页面

                .paths(Predicates.and(PathSelectors.regex("/admin/.*")))

                .build();

    }

  

    private ApiInfo webApiInfo(){

        return new ApiInfoBuilder()

                .title("网站-API文档")

                .description("本文档描述了网站微服务接口定义")

                .version("1.0")

                .contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))

                .build();

    }

  

    private ApiInfo adminApiInfo(){

        return new ApiInfoBuilder()

                .title("后台管理系统-API文档")

                .description("本文档描述了后台管理系统微服务接口定义")

                .version("1.0")

                .contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))

                .build();

    }

  }

(6)在模块service模块中引入service_utils

<dependency>

    <groupId>com.atguigugroupId>

    <artifactId>service_utilsartifactId>

    <version>0.0.1-SNAPSHOTversion>

  dependency>

(7)在hosp模块启动类添加注解

@ComponentScan(basePackages = "com.atguigu")

尚医通02:医院API的CRUD+环境搭建_第27张图片

(8)启动测试

http://localhost:8201/swagger-ui.html

尚医通02:医院API的CRUD+环境搭建_第28张图片

(9)优化

//医院设置接口

  @Api(tags = "医院设置接口")

  @RestController

@RequestMapping("/admin/hosp/hospitalSet")

  public class HospitalSetController {

  

    @Autowired

    private HospitalSetService hospitalSetService;

  

    @ApiOperation(value = "查询所有")

    @GetMapping("findAll")

    public List<HospitalSet> findAll(){

        List<HospitalSet> list = hospitalSetService.list();

        return list;

    }

    @ApiOperation(value = "根据id删除")

    @DeleteMapping("{id}")

    public boolean delHospset(@PathVariable Long id){

        boolean remove = hospitalSetService.removeById(id);

        return remove;

    }

  

  }

尚医通02:医院API的CRUD+环境搭建_第29张图片

统一返回结果

1、json

(1)对象:{“id”:1,”name”:”zhang3”,”age”:33}

(2)数组:

[{“id”:1,”name”:”zhang3”,”age”:33},{“id”:1,”name”:”zhang3”,”age”:33}]

2、封装对象

{

  "success": true,

  "code": 20000,

  "message": "成功",

  "data": {

    "items": [

      {

        "id": "1",

        "name": "刘德华",

        "intro": "毕业于师范大学数学系,热爱教育事业,执教数学思维6年有余"

      }

    ]

  }

}

Success 布尔

Code 数字

Message 字符串

Data  MAP


3、实现统一结果封装

(1)在common模块下创建子模块common_utils

尚医通02:医院API的CRUD+环境搭建_第30张图片

(2)创建包com.atguigu.yygh.common,创建封装类、相关接口



  @Data

  public class R {

    @ApiModelProperty(value = "是否成功")

    private Boolean success;

  

    @ApiModelProperty(value = "返回码")

    private Integer code;

  

    @ApiModelProperty(value = "返回消息")

    private String message;

  

    @ApiModelProperty(value = "返回数据")

    private Map<String, Object> data = new HashMap<String, Object>();

  

    private R(){}

  

    public static R ok(){

        R r = new R();

        r.setSuccess(true);

        r.setCode(ResultCode.SUCCESS);

        r.setMessage("成功");

        return r;

    }

  

    public static R error(){

        R r = new R();

        r.setSuccess(false);

        r.setCode(ResultCode.ERROR);

        r.setMessage("失败");

        return r;

    }

  

    public R success(Boolean success){

        this.setSuccess(success);

        return this;

    }

  

    public R message(String message){

        this.setMessage(message);

        return this;

    }

  

    public R code(Integer code){

        this.setCode(code);

        return this;

    }

  

    public R data(String key, Object value){

        this.data.put(key, value);

        return this;

    }

  

    public R data(Map<String, Object> map){

        this.setData(map);

        return this;

    }

  }

public interface ResultCode {

    public static Integer SUCCESS = 20000;

  

    public static Integer ERROR = 20001;

  }

(3)在service模块中添加依赖

<dependency>

    <groupId>com.atguigugroupId>

    <artifactId>common_utilsartifactId>

    <version>0.0.1-SNAPSHOTversion>

  dependency>

(4)改造方法

@ApiOperation(value = "查询所有")

  @GetMapping("findAll")

  public R findAll(){

    List<HospitalSet> list = hospitalSetService.list();

    return R.ok().data("list",list);

  }

  @ApiOperation(value = "根据id删除")

  @DeleteMapping("{id}")

  public R delHospset(@PathVariable Long id){

    boolean remove = hospitalSetService.removeById(id);

    return R.ok();

  }

(5)测试

尚医通02:医院API的CRUD+环境搭建_第31张图片

尚医通02:医院API的CRUD+环境搭建_第32张图片

实现带条件带分页查询接口

1、需求分析

尚医通02:医院API的CRUD+环境搭建_第33张图片

2、接口分析

*参数:page、limit、HospitalSetQueryVo

*返回值:R(list、total)

尚医通02:医院API的CRUD+环境搭建_第34张图片

3、实现分页查询接口

(1)添加插件

/**

 * 分页插件

 */

  @Bean

  public PaginationInterceptor paginationInterceptor() {

    return new PaginationInterceptor();

  }

(2)实现分页查询

@ApiOperation(value = "分页查询")

  @GetMapping("pageQuery/{page}/{limit}")

  public R pageQuery(@PathVariable Long page,@PathVariable Long limit){

    //1封装分页参数

    Page<HospitalSet> pageParam = new Page<>(page,limit);

    //2实现分页查询

    hospitalSetService.page(pageParam);

    //3取出分页查询结果

    List<HospitalSet> records = pageParam.getRecords();

    long total = pageParam.getTotal();

    //4封装返回

    return R.ok().data("records",records).data("total",total);

  }

(3)测试

尚医通02:医院API的CRUD+环境搭建_第35张图片


4、带条件带分页查询

(1)实现

@ApiOperation(value = "带条件分页查询")

  @PostMapping("pageList/{page}/{limit}")

  public R pageList(@PathVariable Long page, @PathVariable Long limit,

                @RequestBody HospitalSetQueryVo hospitalSetQueryVo){

    //1hospitalSetQueryVo取出参数,拼写查询条件

    String hosname = hospitalSetQueryVo.getHosname();

    String hoscode = hospitalSetQueryVo.getHoscode();

    QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();

    if(!StringUtils.isEmpty(hosname)){

        wrapper.like("hosname",hosname);

    }

    if(!StringUtils.isEmpty(hoscode)){

        wrapper.eq("hoscode",hoscode);

    }

    //2封装分页参数

    Page<HospitalSet> pageParam = new Page<>(page,limit);

    //3实现带条件分页查询

    hospitalSetService.page(pageParam,wrapper);

    //4取出分页查询结果

    List<HospitalSet> records = pageParam.getRecords();

    long total = pageParam.getTotal();

    //5封装返回

    return R.ok().data("records",records).data("total",total);

  }


(2)测试

尚医通02:医院API的CRUD+环境搭建_第36张图片

尚医通02:医院API的CRUD+环境搭建_第37张图片


新增、修改接口开发

1、新增

1)确认需求

尚医通02:医院API的CRUD+环境搭建_第38张图片

(2)分析接口

*参数: HospitalSet

*返回值:R.ok()

(3)实现接口

@ApiOperation(value = "新增医院设置")

  @PostMapping("save")

  public R save(@RequestBody HospitalSet hospitalSet){

    boolean save = hospitalSetService.save(hospitalSet);

    if(save){

        return R.ok();

    }else {

        return R.error();

    }

  }

  1. 修改

(1)需求分析

尚医通02:医院API的CRUD+环境搭建_第39张图片

尚医通02:医院API的CRUD+环境搭建_第40张图片

(2)数据回显接口

*参数:id

*返回值:R(HospitalSet)

(3)修改保存接口

*参数: HospitalSet

*返回值:R.ok()

(4)实现接口

@ApiOperation(value = "根据id查询信息")

  @GetMapping("getById/{id}")

  public R getById(@PathVariable Long id){

    HospitalSet hospitalSet = hospitalSetService.getById(id);

    return R.ok().data("hospitalSet",hospitalSet);

  }

  

  @ApiOperation(value = "修改医院设置")

  @PostMapping("update")

  public R update(@RequestBody HospitalSet hospitalSet){

    boolean update = hospitalSetService.updateById(hospitalSet);

    if(update){

        return R.ok();

    }else {

        return R.error();

    }

  }

(5)测试

尚医通02:医院API的CRUD+环境搭建_第41张图片

尚医通02:医院API的CRUD+环境搭建_第42张图片

批量删除、锁定医院设置

1、批量删除

(1)需求分析

尚医通02:医院API的CRUD+环境搭建_第43张图片

(2)接口分析

*参数:List idList

*返回值:R.ok()

(3)实现

@ApiOperation(value = "根据id集合批量删除")

  @DeleteMapping("delByIds")

  public R delByIds(@RequestBody  List<Long> idList){

    boolean remove = hospitalSetService.removeByIds(idList);

    if(remove){

        return R.ok();

    }else {

        return R.error();

    }

  }

(4)测试

尚医通02:医院API的CRUD+环境搭建_第44张图片

尚医通02:医院API的CRUD+环境搭建_第45张图片

2、锁定医院设置

(1)需求分析

尚医通02:医院API的CRUD+环境搭建_第46张图片

(2)接口分析

*参数:id 、status

*返回值:R.ok()

(3)方法实现

@ApiOperation(value = "医院设置锁定和解锁")

  @PutMapping("lockHospitalSet/{id}/{status}")

  public R lockHospitalSet(@PathVariable Long id,

                         @PathVariable Integer status) {

   //1根据id查询数据

    HospitalSet hospitalSet = hospitalSetService.getById(id);

    //2修改数据

    hospitalSet.setStatus(status);

    hospitalSetService.updateById(hospitalSet);

    return R.ok();

  }

统一异常处理

1、制造异常

尚医通02:医院API的CRUD+环境搭建_第47张图片

尚医通02:医院API的CRUD+环境搭建_第48张图片

我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理

  1. 实现统一异常处理
  1. service_utils引入依赖

(2)在service_utils中创建统一异常处理类GlobalExceptionHandler.java:

/**

 * 统一异常处理类

 */

  @ControllerAdvice

  public class GlobalExceptionHandler {

  

    @ExceptionHandler(Exception.class)

    @ResponseBody

    public R error(Exception e){

        e.printStackTrace();

        return R.error();

    }

  

  }

你可能感兴趣的:(项目,java,后端,微服务)