SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便

1. 建立项目,配置application.yml文件和pom文件

  SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便

 

 pomwen文件(有些根本没用到,所以按上边的加上swagger就行)

<?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.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>study4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>study4</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.22</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

 

2. 配置application.yml文件的数据库配置和MyBatis配置

server:
  port: 8082 
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/mysql_study?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456


mybatis-plus:
  global-config:
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:mapper/*.xml---------这个是resource文件下的mapper,不是主项目的mapper文件夹
  type-aliases-package: com.example.study4.model

 3. 新建实体类,重写toString()方法

package com.example.study4.model;

import java.io.Serializable;

public class User implements Serializable {

    private Integer userid;
    private String username;
    private Integer userage;

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserage() {
        return userage;
    }

    public void setUserage(int userage) {
        this.userage = userage;
    }

    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", username=‘" + username + ‘\‘‘ +
                ", userage=" + userage +
                ‘}‘;
    }
}

4.主项目的mapper文件夹创建接口文件

package com.example.study4.mapper;

import com.example.study4.model.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
    List<User> getAllUsers();

    User getUserById(Integer id);

    int deleteUserById(Integer id);

    void addUser(User user);
}

5. service文件夹创建继承类

package com.example.study4.service;

import com.example.study4.mapper.UserMapper;
import com.example.study4.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements UserMapper {

    @Autowired
    UserMapper userMapper;

    public List<User> getAllUsers(){
        return userMapper.getAllUsers();

    }

    public User getUserById(Integer id){
        return userMapper.getUserById(id);
    }

    public int deleteUserById(Integer id){
        return userMapper.deleteUserById(id);
    }

    public void addUser(User user){
        userMapper.addUser(user);
    }
}

6. 创建控制类并书写控制类方法

package com.example.study4.controller;

import com.example.study4.model.User;
import com.example.study4.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.awt.geom.AreaOp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"用户表增删改查"})
public class UserController {
   @Autowired
    UserService userService;

    @ApiOperation("获取所有用户信息")
    @GetMapping("/getAllUsers")
    public String getAllUsers()
//            @ApiParam(name="user_id",value="用户id",required=true)
//            @RequestParam("user_id")
//                    Integer id)
                    {
        List<User> users = userService.getAllUsers();
        if(users.size()==0){
            return ("用户信息表为空");
        }else {
//        for (User allUser :allUsers) {
//            System.out.println(allUser.toString());
//        }
//        System.out.println(allUsers.toString());
            System.out.println("123");
            return (users.toString());
        }
    }

//    @GetMapping("/getUserById")
//    public Map<String, Object> getUserById(@RequestParam Integer id){
//        User user = userService.getUserById(id);
//        Map<String, Object> result = new HashMap<String, Object>();
//        result.put("user", user);
//        return result;
//    }

    @ApiOperation("根据id获取用户信息")
    @GetMapping("/getUserById")
    public String getUserById(@RequestParam Integer id){
        User user = userService.getUserById(id);
        if(user==null){
            return ("该用户不存在");
        }else {
            return (user.toString());
        }
    }


    @ApiOperation("根据id删除用户信息")
    @GetMapping("/delUserById")
    public int  delUser(@RequestParam Integer id){
        String user=getUserById(id);
        if(user!=null){
            int del = userService.deleteUserById(id);
            return(del);
        } else {
            return -1;
        }




    }

    @ApiOperation(value = "输入用户信息添加用户")
    @GetMapping("/addUser")
    public void addUser(
            @ApiParam(name="userid",value="用户id",required=true)
            @RequestParam("userid")
                    Integer userid,

            @ApiParam(name="username",value="用户姓名",required=true)
            @RequestParam("username")
                    String username,

            @ApiParam(name="userage",value="用户年龄",required=true)
            @RequestParam("userage")
                    Integer userage
    ){
        String user=getUserById(userid);
        if (user==null){

        }else {


            User add_user = new User();
            add_user.setUserid(userid);
            add_user.setUsername(username);
            add_user.setUserage(userage);

            userService.addUser(add_user);

        }
    }
}

7. 集成swagger配置方便测试

package com.example.study4.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.study4"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build());
    }
}

8. 资源文件下新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.study4.mapper.UserMapper">

    <select id="getAllUsers"   resultType="User">   =========id是对应主文件下mapper中的方法
        SELECT * from user_information
    </select>

    <select id="getUserById"  parameterType="Integer" resultType="User">
        select * from user_information where userid=#{id}
    </select>

    <delete id="deleteUserById"  parameterType="int">
        DELETE from user_information where userid=#{id}
    </delete>

    <insert id="addUser" parameterType="User" >
        INSERT into user_information(userid,username,userage) values (#{userid},#{username},#{userage})
    </insert>
</mapper>

9. 最后运行

http://localhost:8082/swagger-ui.html 即可查看对应效果

SpringBoot+Mybatis+mysql 实现增删改查,集成swagger更方便

上一篇:C# mongodb Filter BsonSerializer


下一篇:sql server 日期转字符串