SpringBoot整合Mybatis、Redis和Swagger使用restful风格实现CRUD

SpringBoot整合Mybatis、Redis和Swagger使用restful风格实现CRUD

一、概述

最近在做一个SpringBoot的项目,距离上一次做已经有一段时间了,现在进行一个总结,总体来说比较通用,也可以算作一个Demo,具体的需求就是增删改查

总体步骤是这样的:创建springboot项目 --> 导入相应的依赖 --> 进行相关配置 --> 编写entity、mapper接口和mapper.xml映射文件 --> 测试mapper --> 编写service和controller -> 通过swagger进行测试

二、项目目录结构

SpringBoot整合Mybatis、Redis和Swagger使用restful风格实现CRUD_第1张图片

三、具体的代码

  1. pom文件

    
    <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.4.2version>
            <relativePath/> 
        parent>
        <groupId>com.vernhe.springbootgroupId>
        <artifactId>project01artifactId>
        <version>0.0.1-SNAPSHOTversion>
        <name>project01name>
        <description>Demo project for Spring Bootdescription>
        <properties>
            <java.version>1.8java.version>
        properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
                <version>2.1.4version>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druid-spring-boot-starterartifactId>
                <version>1.1.10version>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-redisartifactId>
            dependency>
            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.9.2version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.9.2version>
            dependency>
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombokgroupId>
                                <artifactId>lombokartifactId>
                            exclude>
                        excludes>
                    configuration>
                plugin>
            plugins>
        build>
    
    project>
    
    
  2. application.yml配置文件

    server:
      port: 8080
    
    spring:
      datasource:
        url: jdbc:mysql://127.0.0.1:3306/realProject?useUnicode=true&characterEncoding=utf-8
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
      redis:
        host: 127.0.0.1
        port: 6379
        jedis:
          pool:
            max-active: 8
            max-wait: -1
            max-idle: 500
            min-idle: 0
    
    
    mybatis:
      mapper-locations: classpath:mapper/*.xml
    
    logging:
      level:
        com.vernhe.springboot.project01.mapper: debug
    
    
  3. entity实体类(注解是swagger的注解,等到第8步完成后再加)

    @Data
    @ApiModel("Tag对象模型")
    public class Tag {
           
    
        @ApiModelProperty("id")
        private String id;
    
        @ApiModelProperty("目标")
        private String tagTo;
    
        @ApiModelProperty("名字")
        private String name;
    }
    
  4. mapper接口(两种方式)

    一、配合注解使用

    TagMapper.java

    public interface TagMapper {
           
        @Select("select * from tag")
        List<Tag> getAllTag();
    }
    

    二、配合XXXMapper.xml文件使用

    TagMapper2.java

    public interface TagMapper2 {
           
        List<Tag> getAllTag();
    
        Integer addTag(Tag tag);
    
        Integer updateTagById(Tag tag);
    
        Integer deleteTagById(String id);
    }
    

    TagMapper.xml

    
    
    
    <mapper namespace="com.vernhe.springboot.project01.mapper.TagMapper2">
        <insert id="addTag"
                parameterType="com.vernhe.springboot.project01.entity.Tag">
            insert into tag (Id,TagTo,Name) values (#{id},#{tagTo},#{name});
        insert>
    
        <update id="updateTagById"
                parameterType="com.vernhe.springboot.project01.entity.Tag">
            update tag set TagTo=#{tagTo},Name=#{name} where Id=#{id};
        update>
    
        <delete id="deleteTagById">
            delete from tag where Id = #{id};
        delete>
    
        <select id="getAllTag" resultType="com.vernhe.springboot.project01.entity.Tag">
            select * from tag;
        select>
    mapper>
    
  5. 对编写好的mapper进行测试

    @SpringBootTest
    class Project01ApplicationTests {
           
    
        @Autowired
        TagMapper mapper1;
        @Autowired
        TagMapper2 mapper2;
        @Autowired
        RedisTemplate<String, String> redisTemplate;
    
        @Test
        void test1() {
           
            // 注解方式
            System.out.println(mapper1.getAllTag());
        }
    
        @Test
        void test2() {
           
            // xml映射文件方式 查询
            System.out.println(mapper2.getAllTag());
        }
        
        // 其他测试的法这里暂时省略
    }
    
  6. 编写service接口

    public interface TagService {
           
        List<Tag> getAllTag();
    
        Integer addTag(Tag tag);
    
        Integer updateTagById(Tag tag);
    
        Integer deleteTagById(String id);
    }
    
  7. 编写serviceImpl实现类

    @Service
    public class TagServiceImpl implements TagService {
           
        @Autowired
        private TagMapper2 tagMapper;
    
        @Override
        public List<Tag> getAllTag() {
           
            return tagMapper.getAllTag();
        }
    
        @Override
        public Integer addTag(Tag tag) {
           
            return tagMapper.addTag(tag);
        }
    
        @Override
        public Integer updateTagById(Tag tag) {
           
            return tagMapper.updateTagById(tag);
        }
    
        @Override
        public Integer deleteTagById(String id) {
           
            return tagMapper.deleteTagById(id);
        }
    }
    
  8. 编写Swagger配置类SwaggerConfig

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
           
    
        @Bean
        public Docket creatRestApi() {
           
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                .apis(RequestHandlerSelectors.basePackage("com.vernhe.springboot.project01")) //swagger的搜索的包
                    .paths(PathSelectors.any()) //swagger的路径匹配规则
                    .build();
        }
    
        private ApiInfo apiInfo() {
           
            return new ApiInfoBuilder()
                    .title("SpringBoot-CRUD文档")
                    .description("使用swagger生成文档")
                    .version("version 1.0")
                    .build();
        }
    
    }
    
  9. 编写Controller

    @Controller
    @RequestMapping("/tag")
    @Api(tags = "Tag管理API")
    public class TagController {
           
        @Autowired
        TagService tagService;
    
        @DeleteMapping("/delete/{id}")
        @ResponseBody
        @ApiOperation(value = "删除Tag", notes = "删除接口")
        @ApiResponses({
           
                @ApiResponse(code = 200, message = "删除成功"),
                @ApiResponse(code = 400, message = "id不存在或者格式不正确")
        })
        public ResponseEntity<String> deleteTag(@PathVariable("id") String id) {
           
            Integer result = tagService.deleteTagById(id);
            if (result > 0) {
           
                return ResponseEntity.ok(id);
            } else {
           
                return new ResponseEntity(id, HttpStatus.BAD_REQUEST);
            }
        }
    
        @GetMapping("/getall")
        @ResponseBody
        @ApiOperation(value = "查询Tag", notes = "查询接口")
        @ApiResponses({
           
                @ApiResponse(code = 200, message = "查询成功"),
                @ApiResponse(code = 400, message = "查询失败")
        })
        public ResponseEntity<List<Tag>> findAllTag() {
           
            List<Tag> tags = tagService.getAllTag();
            if (tags == null) {
           
                return new ResponseEntity(400,HttpStatus.BAD_REQUEST);
            } else {
           
                return ResponseEntity.ok(tags);
            }
        }
    
        @PostMapping
        @ResponseBody
        @ApiOperation(value = "添加Tag", notes = "添加接口")
        @ApiResponses({
           
                @ApiResponse(code = 200, message = "添加成功"),
                @ApiResponse(code = 400, message = "添加失败"),
                @ApiResponse(code = 401, message = "权限不足"),
        })
        public ResponseEntity<Tag> addTag(Tag tag) {
           
            if (tag == null) {
           
                return new ResponseEntity(400,HttpStatus.BAD_REQUEST);
            }
            Integer result = tagService.addTag(tag);
            if (result > 0) {
           
                return ResponseEntity.ok(tag);
            } else {
           
                return new ResponseEntity<>(tag, HttpStatus.UNAUTHORIZED);
            }
        }
    
        @PutMapping
        @ResponseBody
        @ApiOperation(value = "更新Tag", notes = "更新接口")
        @ApiResponses({
           
                @ApiResponse(code = 200, message = "更新成功"),
                @ApiResponse(code = 400, message = "更新失败"),
                @ApiResponse(code = 401, message = "权限不足")
        })
        public ResponseEntity<Tag> updateTag(Tag tag) {
           
            if (tag == null) {
           
                return new ResponseEntity(400,HttpStatus.BAD_REQUEST);
            }
            Integer result = tagService.updateTagById(tag);
            if (result > 0) {
           
                return ResponseEntity.ok(tag);
            } else {
           
                return new ResponseEntity<>(tag, HttpStatus.UNAUTHORIZED);
            }
        }
    
    }
    
  10. 启动项目,浏览器打开http://localhost:8080/swagger-ui.html#进入swagger文档的界面,如下图所示


    SpringBoot整合Mybatis、Redis和Swagger使用restful风格实现CRUD_第2张图片

你可能感兴趣的:(框架学习,spring,boot,mybatis,redis,swagger2,restful)