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

目录

今日必会

项目环境搭建

医院设置模块搭建

配置使用Swagger2

统一返回结果

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

新增、修改接口开发

批量删除、锁定医院设置

统一异常处理


今日必会

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

        yygh_parent         <pom>

        common               <pom>

        model                    无                                 

        service                 <pom>


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()


  ※批量删除 参数:list<long>idlis   返回值: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<HospitalSet> 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<HospitalSet> pageparm = new Page<>(page,limit);
       //2.实现分页查询
      hospitalSetService.page(pageparm);
      //3.取出结果
      List<HospitalSet> 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<HospitalSet> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(hosname)){

            wrapper.like("hosname",hosname);


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

            wrapper.eq("hoscode",hoscode);

        }
        //1.封装分页参数
        Page<HospitalSet> pageparm = new Page<>(page,limit);
        //2.实现分页查询
        hospitalSetService.page(pageparm,wrapper);
        //3.取出结果
        List<HospitalSet> 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<Long> 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、项目开发方式

前后端分离

2、后端工程分层

(1)分类

*jar:java工程

*war:web工程

*pom:父工程

(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='用户登录记录表';


(2)数据库设计规范

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

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


3、工程结构介绍


4、创建父工程

(1)创建springboot工程yygh_parent

(2)修改pom.xml

<?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.0</modelVersion>

  

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.2.1.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.atguigu</groupId>

    <artifactId>yygh_parent</artifactId>

    <packaging>pom</packaging>

    <version>0.0.1-SNAPSHOT</version>

    <name>yygh_parent</name>

    <description>Demo project for Spring Boot</description>

    <properties>

        <java.version>1.8</java.version>

        <cloud.version>Hoxton.RELEASE</cloud.version>

        <alibaba.version>2.2.0.RELEASE</alibaba.version>

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

        <mysql.version>5.1.46</mysql.version>

        <swagger.version>2.7.0</swagger.version>

        <jwt.version>0.7.0</jwt.version>

        <fastjson.version>1.2.29</fastjson.version>

        <httpclient.version>4.5.1</httpclient.version>

        <easyexcel.version>2.2.0-beta2</easyexcel.version>

        <aliyun.version>4.1.1</aliyun.version>

        <oss.version>3.9.1</oss.version>

        <jodatime.version>2.10.1</jodatime.version>

    </properties>

  

    <!--配置dependencyManagement锁定依赖的版本-->

    <dependencyManagement>

        <dependencies>

            <dependency>

                <groupId>org.springframework.cloud</groupId>

                <artifactId>spring-cloud-dependencies</artifactId>

                <version>${cloud.version}</version>

                <type>pom</type>

                <scope>import</scope>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba.cloud</groupId>

                <artifactId>spring-cloud-alibaba-dependencies</artifactId>

                <version>${alibaba.version}</version>

                <type>pom</type>

                <scope>import</scope>

            </dependency>

  

            <!--mybatis-plus 持久层-->

            <dependency>

                <groupId>com.baomidou</groupId>

                <artifactId>mybatis-plus-boot-starter</artifactId>

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

            </dependency>

  

            <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>${mysql.version}</version>

            </dependency>

  

            <!--swagger-->

            <dependency>

                <groupId>io.springfox</groupId>

                <artifactId>springfox-swagger2</artifactId>

                <version>${swagger.version}</version>

            </dependency>

            <!--swagger ui-->

            <dependency>

                <groupId>io.springfox</groupId>

                <artifactId>springfox-swagger-ui</artifactId>

                <version>${swagger.version}</version>

            </dependency>

  

            <dependency>

                <groupId>io.jsonwebtoken</groupId>

                <artifactId>jjwt</artifactId>

                <version>${jwt.version}</version>

            </dependency>

  

            <dependency>

                <groupId>org.apache.httpcomponents</groupId>

                <artifactId>httpclient</artifactId>

                <version>${httpclient.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>fastjson</artifactId>

                <version>${fastjson.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>easyexcel</artifactId>

                <version>${easyexcel.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.aliyun</groupId>

                <artifactId>aliyun-java-sdk-core</artifactId>

                <version>${aliyun.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.aliyun.oss</groupId>

                <artifactId>aliyun-sdk-oss</artifactId>

                <version>${oss.version}</version>

            </dependency>

  

            <!--日期时间工具-->

            <dependency>

                <groupId>joda-time</groupId>

                <artifactId>joda-time</artifactId>

                <version>${jodatime.version}</version>

            </dependency>

        </dependencies>

    </dependencyManagement>

  

    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

  

  </project>

<?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.0</modelVersion>

  

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.2.1.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.atguigu</groupId>

    <artifactId>yygh_parent</artifactId>

    <packaging>pom</packaging>

    <version>0.0.1-SNAPSHOT</version>

    <name>yygh_parent</name>

    <description>Demo project for Spring Boot</description>

    <properties>

        <java.version>1.8</java.version>

        <cloud.version>Hoxton.RELEASE</cloud.version>

        <alibaba.version>2.2.0.RELEASE</alibaba.version>

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

        <mysql.version>5.1.46</mysql.version>

        <swagger.version>2.7.0</swagger.version>

        <jwt.version>0.7.0</jwt.version>

        <fastjson.version>1.2.29</fastjson.version>

        <httpclient.version>4.5.1</httpclient.version>

        <easyexcel.version>2.2.0-beta2</easyexcel.version>

        <aliyun.version>4.1.1</aliyun.version>

        <oss.version>3.9.1</oss.version>

        <jodatime.version>2.10.1</jodatime.version>

    </properties>

  

    <!--配置dependencyManagement锁定依赖的版本-->

    <dependencyManagement>

        <dependencies>

            <dependency>

                <groupId>org.springframework.cloud</groupId>

                <artifactId>spring-cloud-dependencies</artifactId>

                <version>${cloud.version}</version>

                <type>pom</type>

                <scope>import</scope>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba.cloud</groupId>

                <artifactId>spring-cloud-alibaba-dependencies</artifactId>

                <version>${alibaba.version}</version>

                <type>pom</type>

                <scope>import</scope>

            </dependency>

  

            <!--mybatis-plus 持久层-->

            <dependency>

                <groupId>com.baomidou</groupId>

                <artifactId>mybatis-plus-boot-starter</artifactId>

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

            </dependency>

  

            <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>${mysql.version}</version>

            </dependency>

  

            <!--swagger-->

            <dependency>

                <groupId>io.springfox</groupId>

                <artifactId>springfox-swagger2</artifactId>

                <version>${swagger.version}</version>

            </dependency>

            <!--swagger ui-->

            <dependency>

                <groupId>io.springfox</groupId>

                <artifactId>springfox-swagger-ui</artifactId>

                <version>${swagger.version}</version>

            </dependency>

  

            <dependency>

                <groupId>io.jsonwebtoken</groupId>

                <artifactId>jjwt</artifactId>

                <version>${jwt.version}</version>

            </dependency>

  

            <dependency>

                <groupId>org.apache.httpcomponents</groupId>

                <artifactId>httpclient</artifactId>

                <version>${httpclient.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>fastjson</artifactId>

                <version>${fastjson.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>easyexcel</artifactId>

                <version>${easyexcel.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.aliyun</groupId>

                <artifactId>aliyun-java-sdk-core</artifactId>

                <version>${aliyun.version}</version>

            </dependency>

  

            <dependency>

                <groupId>com.aliyun.oss</groupId>

                <artifactId>aliyun-sdk-oss</artifactId>

                <version>${oss.version}</version>

            </dependency>

  

            <!--日期时间工具-->

            <dependency>

                <groupId>joda-time</groupId>

                <artifactId>joda-time</artifactId>

                <version>${jodatime.version}</version>

            </dependency>

        </dependencies>

    </dependencyManagement>

  

    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

  

  </project>

(3)删除src

5、搭建model模块

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

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

<dependencies>

    <dependency>

        <groupId>org.projectlombok</groupId>

        <artifactId>lombok</artifactId>

    </dependency>

    <!--mybatis-plus-->

    <dependency>

        <groupId>com.baomidou</groupId>

        <artifactId>mybatis-plus-boot-starter</artifactId>

        <scope>provided </scope>

    </dependency>

    <!--swagger-->

    <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

        <scope>provided </scope>

    </dependency>

    <dependency>

        <groupId>com.alibaba</groupId>

        <artifactId>easyexcel</artifactId>

        <scope>provided </scope>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-mongodb</artifactId>

        <scope>provided </scope>

    </dependency>

    <dependency>

        <groupId>com.alibaba</groupId>

        <artifactId>fastjson</artifactId>

        <scope>provided </scope>

    </dependency>

  </dependencies>

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

6、搭建service模块

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

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

<dependencies>

    <dependency>

        <groupId>com.atguigu</groupId>

        <artifactId>model</artifactId>

        <version>0.0.1-SNAPSHOT</version>

    </dependency>

    <!--web-->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <!--mybatis-plus-->

    <dependency>

        <groupId>com.baomidou</groupId>

        <artifactId>mybatis-plus-boot-starter</artifactId>

    </dependency>

    <!--mysql-->

    <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

    </dependency>

    <!--开发者工具-->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <optional>true</optional>

    </dependency>

    <!-- 服务调用feign

    <dependency>

        <groupId>org.springframework.cloud</groupId>

        <artifactId>spring-cloud-starter-openfeign</artifactId>

    </dependency>-->

    <!-- 服务注册

    <dependency>

        <groupId>com.alibaba.cloud</groupId>

        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

    </dependency>-->

  </dependencies>

(3)删除src


7、搭建医院模块service_hosp模块


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

医院设置模块搭建
  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)创建主目录、启动类


@SpringBootApplication

  public class ServiceHospApplication {

    public static void main(String[] args) {

        SpringApplication.run(ServiceHospApplication.class,args);

    }

  }

3、搭建MP框架

(1)确认实体

(2)搭建mapper

 


public interface HospitalSetMapper extends BaseMapper<HospitalSet> {

}

(3)搭建service

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)启动测试


(7)实现删除

@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父模块

(2)修改pom,引入依赖


<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

        <scope>provided </scope>

    </dependency>

  

    <!--mybatis-plus-->

    <dependency>

        <groupId>com.baomidou</groupId>

        <artifactId>mybatis-plus-boot-starter</artifactId>

        <scope>provided </scope>

    </dependency>

  

    <!--lombok用来简化实体类:需要安装lombok插件-->

    <dependency>

        <groupId>org.projectlombok</groupId>

        <artifactId>lombok</artifactId>

    </dependency>

  

    <!--swagger-->

    <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

    </dependency>

    <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger-ui</artifactId>

    </dependency>

  

    <dependency>

        <groupId>com.alibaba</groupId>

        <artifactId>fastjson</artifactId>

    </dependency>

  </dependencies>

(3)删除src

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

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


@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.atguigu</groupId>

    <artifactId>service_utils</artifactId>

    <version>0.0.1-SNAPSHOT</version>

  </dependency>

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

@ComponentScan(basePackages = "com.atguigu")

(8)启动测试

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

(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;

    }

  

  }

统一返回结果

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

(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.atguigu</groupId>

    <artifactId>common_utils</artifactId>

    <version>0.0.1-SNAPSHOT</version>

  </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)测试

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

1、需求分析

2、接口分析

*参数:page、limit、HospitalSetQueryVo

*返回值:R(list、total)

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)测试


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)测试


新增、修改接口开发

1、新增

1)确认需求

(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)需求分析

(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)测试

批量删除、锁定医院设置

1、批量删除

(1)需求分析

(2)接口分析

*参数:List<Long> 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)测试

2、锁定医院设置

(1)需求分析

(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、制造异常

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

  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();

    }

  

  }

猜你喜欢

转载自blog.csdn.net/leader_song/article/details/131645890
今日推荐