Springboot整合mybatis+pageHelper+swagger3实现增删改查

一、新建数据库表

Emp

字段

类型

长度

主键

自增

备注

id

int

 

Y

Y

 

name

varchar

255

 

 

 

addr

varchar

255

 

 

 

dept

Varchar

255

 

 

 

age

int

 

 

 

 

 

使用springboot整合mybatis+pageHelper+swagger3,完成如下要求:

1、对数据库表的增加

2、对数据库表给定id删除

3、对数据库表按给定条件删除(思考)

4、对数据库表按给定id修改

5、对数据库表显示全部数据

6、对数据库表分页显示全部数据

7、对数据库表按给定id查询数据

8、对数据库表按给定条件分页查询数据(思考)

 

二、使用mybatis-plus整合mybatis,完成如下要求

1、对数据库表的增加

2、对数据库表按给定id删除

3、对数据库表的全部显示

 

新建一个Spring Initializr的自带模板的Moduel

 

 点击Next,添加需要用到的依赖

 配置pom.xml,新增swgger3和分页插件的依赖

<?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>
    <groupId>com.xzit</groupId>
    <artifactId>day4_job</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>day4_job</name>
    <description>day4_job</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!--springboot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis整合springboot-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!--热启动-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 引入swagger3(springfox)的依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.xzit.Day4JobApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

新建一个application.yml配文件,删掉原来的application.properties配置文件

#处理swagger异常
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
#配置数据库连接相关属性
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8
    username: root
    password: zengyu1234

#mybatis配置控制台打印完整带参数SQL语句的实现
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

新建一个员工实体类:

package com.xzit.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("员工对象")
public class Emp {
    @ApiModelProperty("员工id")
    private int id;
    @ApiModelProperty("员工姓名")
    private String name;
    @ApiModelProperty("员工地址")
    private String addr;
    @ApiModelProperty("员工部门")
    private String dept;
    @ApiModelProperty("员工年龄")
    private int age;
}

复制一个swagger3配置类

package com.xzit.config;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

//bean.xml applicationContext.xml
//<bean id="" class="">
@Configuration
public class Swagger3Config {
    @Bean
    public Docket apiConfig(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //设置通过什么方式定位到需要生成文档的接口,
                //定位了方法上的ApiOperation
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //接口URL路径,any表示全部的路径
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("伊万的项目")
                .description("项目描述信息")
                .contact(new Contact("伊万","http://www.baidu.com","2342342456qq.com"))
                .version("1.0")
                .build();
    }
}

先从mapper接口类开始写,新建一个EmpMapper接口类把SQL查询语句都写上

package com.xzit.mapper;

import com.xzit.entity.Emp;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface EmpMapper {
    @Select("select * from emp")
    List<Emp> selectList();

    @Select("select * from emp where id = #{id}")
    Emp selectId(Integer id);

    @Insert("insert into emp values(null,#{name},#{addr},#{dept},#{age})")
    int save(Emp emp);

    @Update("update emp set name=#{name},addr=#{addr},dept=#{dept},age=#{age} where id=#{id}")
    int update(Emp emp);

    @Delete("delete from emp where id=#{id}")
    int delete(Integer id);
}

接着写Service层的接口类

package com.xzit.service;

import com.xzit.entity.Emp;

import java.util.List;

public interface EmpService {
    List<Emp> selectList();
    Emp selectId(Integer id);
    int save(Emp emp);
    int update(Emp emp);
    int delete(Integer id);
}

写一个Service层接口的实现类,执行mapper里的功能

package com.xzit.service.impl;

import com.xzit.entity.Emp;
import com.xzit.mapper.EmpMapper;
import com.xzit.service.EmpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpMapper mapper;

    @Override
    public List<Emp> selectList() {
        return mapper.selectList();
    }

    @Override
    public Emp selectId(Integer id) {
        return mapper.selectId(id);
    }

    @Override
    public int save(Emp emp) {
        return mapper.save(emp);
    }

    @Override
    public int update(Emp emp) {
        return mapper.update(emp);
    }

    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }
}

最后写上Controller,调用service层的方法

package com.xzit.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzit.entity.Emp;
import com.xzit.service.EmpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("emp")
@Api(tags = {"员工管理控制器"})
public class EmpController {
    @Resource
    private EmpService service;

    @ApiModelProperty("分页显示学生信息")
    @GetMapping("/{start}/{size}")
    public Object listByPage(@PathVariable Integer start,@PathVariable Integer size){
        PageHelper.startPage(start,size);
        List<Emp> list=service.selectList();
        PageInfo<Emp> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @ApiOperation("显示全部员工信息")
    @GetMapping
    public Object list(){
        List<Emp> list=service.selectList();
        return list;
    }

    @ApiOperation("按给定的id显示员工信息")
    @GetMapping("/{id}")
    public Object selectId(@PathVariable Integer id){
        Emp emp=service.selectId(id);
        return emp;
    }

    @ApiOperation("保存员工信息")
    @PostMapping
    public Object save(@RequestBody Emp emp){
        int i = service.save(emp);
        return i;
    }

    @ApiOperation("修改员工信息")
    @PutMapping
    public Object update(@RequestBody Emp emp){
        int i = service.update(emp);
        return i;
    }

    @ApiOperation("按给定的id删除员工信息")
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Integer id){
        int i = service.delete(id);
        return i;
    }
}

思考题3:对数据库表按给定条件删除(思考)准备实现一个按照地址查询员工的功能

思考题8:对数据库表按给定条件分页查询数据(思考)准备实现一个按照地址分页查询员工的功能。因为没办法在controller层加查询条件,所以还是把查询条件加在了mapper里,使用

concat('%',#{addr},'%')的方式进行条件的模糊查询

先写好mapper:

package com.xzit.mapper;

import com.xzit.entity.Emp;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface EmpMapper {
    /*查询所有员工*/
    @Select("select * from emp")
    List<Emp> selectList();

    /*按给定地址查询员工*/
    @Select("select * from emp where addr like concat('%',#{addr},'%')")
    List<Emp> selectListByAddr(String addr);

    /*按给定id查询员工*/
    @Select("select * from emp where id = #{id}")
    Emp selectId(Integer id);

    /*往数据库里插入员工*/
    @Insert("insert into emp values(null,#{name},#{addr},#{dept},#{age})")
    int save(Emp emp);

    /*按照id更新指定的员工信息*/
    @Update("update emp set name=#{name},addr=#{addr},dept=#{dept},age=#{age} where id=#{id}")
    int update(Emp emp);

    /*按照id删除员工*/
    @Delete("delete from emp where id=#{id}")
    int delete(Integer id);

    /*按照给定地址查询员工*/
    @Select("select * from emp where addr like concat('%',#{addr},'%')")
    List<Emp> selectAddr(String addr);
}

再写上Service层接口的方法和实现类

package com.xzit.service;

import com.xzit.entity.Emp;

import java.util.List;

public interface EmpService {
    List<Emp> selectList();
    List<Emp> selectListByAddr(String addr);
    Emp selectId(Integer id);
    int save(Emp emp);
    int update(Emp emp);
    int delete(Integer id);
    List<Emp> selectAddr(String addr);
}
package com.xzit.service.impl;

import com.xzit.entity.Emp;
import com.xzit.mapper.EmpMapper;
import com.xzit.service.EmpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpMapper mapper;

    @Override
    public List<Emp> selectList() {
        return mapper.selectList();
    }

    @Override
    public List<Emp> selectListByAddr(String addr) {
        return mapper.selectListByAddr(addr);
    }

    @Override
    public Emp selectId(Integer id) {
        return mapper.selectId(id);
    }

    @Override
    public int save(Emp emp) {
        return mapper.save(emp);
    }

    @Override
    public int update(Emp emp) {
        return mapper.update(emp);
    }

    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }

    @Override
    public List<Emp> selectAddr(String addr) {
        return mapper.selectAddr(addr);
    }
}

最终写上Controller完成

package com.xzit.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzit.entity.Emp;
import com.xzit.service.EmpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("emp")
@Api(tags = {"员工管理控制器"})
public class EmpController {
    @Resource
    private EmpService service;

    @ApiModelProperty("分页显示员工信息")
    @GetMapping("/{start}/{size}")
    public Object listByPage(@PathVariable Integer start,@PathVariable Integer size){
        PageHelper.startPage(start,size);
        List<Emp> list=service.selectList();
        PageInfo<Emp> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @ApiModelProperty("按地址查询并分页显示员工信息")
    @GetMapping("/{start}/{size}/{addr}")
    public Object listByPage(@PathVariable Integer start,@PathVariable Integer size,@PathVariable String addr){
        PageHelper.startPage(start,size);
        List<Emp> list=service.selectListByAddr(addr);
        PageInfo<Emp> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @ApiOperation("显示全部员工信息")
    @GetMapping
    public Object list(){
        List<Emp> list=service.selectList();
        return list;
    }

    @ApiOperation("按给定的id显示员工信息")
    @GetMapping("/{id}")
    public Object selectId(@PathVariable Integer id){
        Emp emp=service.selectId(id);
        return emp;
    }

    @ApiOperation("保存员工信息")
    @PostMapping
    public Object save(@RequestBody Emp emp){
        int i = service.save(emp);
        return i;
    }

    @ApiOperation("修改员工信息")
    @PutMapping
    public Object update(@RequestBody Emp emp){
        int i = service.update(emp);
        return i;
    }

    @ApiOperation("按给定的id删除员工信息")
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Integer id){
        int i = service.delete(id);
        return i;
    }

    @ApiOperation("按给定地址查询员工信息")
    @GetMapping("/userAddr/{addr}")
    public Object selectAddr(@PathVariable String addr){
        List<Emp> empList=service.selectAddr(addr);
        return empList;
    }
}

 

posted @ 2022-08-13 23:12  伊万  阅读(214)  评论(0编辑  收藏  举报