欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 学习笔记

程序员文章站 2022-07-10 18:10:52
...

spring boot整合mybatis和swagger2

开发软件:IDEA

首先创建spring项目

选择spring initializr

spring boot 学习笔记

编辑group和artifact,点击next

spring boot 学习笔记

添加相关依赖,加入mybatis的依赖

spring boot 学习笔记

创建成功后的项目结构:

spring boot 学习笔记

简单看一下这几个文件都是干啥的

ProjectApplication

spring boot 学习笔记

@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。

系统会去入口类的同级包以及下级包中去扫描实体类,因此我们建议入口类的位置在groupId+arctifactID组合的包名下。

如果我们只想要@SpringBootApplication去扫描特定的类而不是全部类,那么就可以关闭自动配置,如下:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

application.properties

Spring Boot使用一个全局的配置文件application.properties或者application.yml,配置文件放在src/main/resources目录下。properties是我们常见的一种配置文件,Spring Boot不仅支持properties这种类型的配置文件,也支持yaml语言的配置文件

pom.xml

一个基本项目的pom.xml文件,通常至少有三个部分

第一部分,项目坐标,信息描述等

第二部分,引入jar包

第三部分,构建项目

准备工作

创建文件目录 

controller放请求接口

dao目录存放和mapper匹配的操作数据库的接口

model是实体类

service里面放具体业务的接口和实现

generator放代码自动生成的配置文件

mapper放操作数据库的xml

spring boot 学习笔记

接下来开始配置框架

>补全pom.xml里面的jar和插件


  1. <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
    
       <groupId>com.springboot</groupId>
       <artifactId>project</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>jar</packaging>
    
       <name>project</name>
       <description>Demo project for Spring Boot</description>
    
       <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.0.2.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
       </parent>
    
       <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
          <java.version>1.8</java.version>
       </properties>
    
       <dependencies>
          <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>1.3.2</version>
          </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>
    
          <!--补全jar-->
    
          <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
             <version>3.4</version>
          </dependency>
    
    
          <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-core</artifactId>
          </dependency>
          <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
          </dependency>
          <dependency>
             <groupId>com.fasterxml.jackson.datatype</groupId>
             <artifactId>jackson-datatype-joda</artifactId>
          </dependency>
          <dependency>
             <groupId>com.fasterxml.jackson.module</groupId>
             <artifactId>jackson-module-parameter-names</artifactId>
          </dependency>
          <!-- 分页插件 -->
          <dependency>
             <groupId>com.github.pagehelper</groupId>
             <artifactId>pagehelper-spring-boot-starter</artifactId>
             <version>1.2.5</version>
          </dependency>
          <!-- alibabadruid数据库连接池 -->
          <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>druid-spring-boot-starter</artifactId>
             <version>1.1.9</version>
          </dependency>
    
       </dependencies>
    
       <build>
          <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
             <!-- mybatis generator 自动生成代码插件 -->
             <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                   <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                   <overwrite>true</overwrite>
                   <verbose>true</verbose>
                </configuration>
             </plugin>
          </plugins>
       </build>
    
    
    </project>

在generator文件夹下,添加generatorConfig.xml

配置项目启动类

package com.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.springboot.dao")
public class ProjectApplication {
   public static void main(String[] args) {
      SpringApplication.run(ProjectApplication.class, args);
   }
}

配置

本文使用application.yml,所以删掉application.properties,创建application.yml

server:
  port: 8080


spring:
    datasource:
        name: mysql_test
        type: com.alibaba.druid.pool.DruidDataSource
        #druid相关配置
        druid:
          #监控统计拦截的filters
          filters: stat
          driver-class-name: com.mysql.jdbc.Driver
          #基本属性
          url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
          username: root
          password: root
          #配置初始化大小/最小/最大
          initial-size: 1
          min-idle: 1
          max-active: 20
          #获取连接等待超时时间
          max-wait: 60000
          #间隔多久进行一次检测,检测需要关闭的空闲连接
          time-between-eviction-runs-millis: 60000
          #一个连接在池中最小生存的时间
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          #打开PSCache,并指定每个连接上PSCache的大小。oracle设为truemysql设为false。分库分表较多推荐设置为false
          pool-prepared-statements: false
          max-pool-prepared-statement-per-connection-size: 20

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.springboot.model

#pagehelper
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

mybatis的部分,根据自己的文件夹名称去配置

创建数据库和数据表

CREATE DATABASE mytest;

CREATE TABLE t_user( userId INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 

userName VARCHAR(255) NOT NULL ,  

password VARCHAR(255) NOT NULL ,

phone VARCHAR(255) NOT NULL

ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;


配置generatorConfig.xml 自动生成与数据库对应的实体类和mapper

  1. <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <generatorConfiguration>
        <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
        <classPathEntry  location="E:\mybatis-generator-core-1.3.2\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
        <context id="DB2Tables"  targetRuntime="MyBatis3">
            <commentGenerator>
                <property name="suppressDate" value="true"/>
                <!-- 是否去除自动生成的注释 true:是 : false:-->
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!--数据库链接URL,用户名、密码 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root">
            </jdbcConnection>
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
            <!-- 生成模型的包名和位置-->
            <javaModelGenerator targetPackage="com.springboot.model" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
            <!-- 生成映射文件的包名和位置-->
            <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
            <!-- 生成DAO的包名和位置-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.springboot.dao" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
            <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
            <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        </context>
    </generatorConfiguration>

   配置generator

   选择run->Edit Configurations

spring boot 学习笔记

添加maven,在Command line输入mybatis-generator:generate -e

spring boot 学习笔记

添加成功后,运行generator,生成对应文件

spring boot 学习笔记


User.java

public class User {
    private Integer userid;

    private String username;

    private String password;

    private String phone;

    public Integer getUserid() {
        return userid;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}


UserMapper.java

public interface UserMapper {
    int deleteByPrimaryKey(Integer userid);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userid);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    //自己添加的方法
    List<User> selectUsers();
}


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.springboot.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.springboot.model.User" >
    <id column="userId" property="userid" jdbcType="INTEGER" />
    <result column="userName" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    userId, userName, password, phone
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where userId = #{userid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_user
    where userId = #{userid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.springboot.model.User" >
    insert into t_user (userId, userName, password, 
      phone)
    values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{phone,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.springboot.model.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userid != null" >
        userId,
      </if>
      <if test="username != null" >
        userName,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="phone != null" >
        phone,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userid != null" >
        #{userid,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        #{phone,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springboot.model.User" >
    update t_user
    <set >
      <if test="username != null" >
        userName = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        phone = #{phone,jdbcType=VARCHAR},
      </if>
    </set>
    where userId = #{userid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.springboot.model.User" >
    update t_user
    set userName = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR}
    where userId = #{userid,jdbcType=INTEGER}
  </update>

  <select id="selectUsers" resultType="com.springboot.model.User">
    SELECT
    <include refid="Base_Column_List"/>
    FROM
    t_user
  </select>
</mapper>

接下来开始我们的业务层

添加UserService和UserServiceImpl的实现代码

UserService.java

public interface UserService {

    int addUser(User user);

    PageInfo<User> findAllUser(int pageNum, int pageSize);
}


UserServiceImpl.java

@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userDao;//这里会报错,但是并不会影响

    @Override
    public int addUser(User user) {
        return userDao.insert(user);
    }

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public PageInfo<User> findAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<User> userDomains = userDao.selectUsers();
        PageInfo result = new PageInfo(userDomains);
        return result;
    }
}

写个接口

在Controller文件夹下创建接口

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;
    @ResponseBody
    @GetMapping("/add")
    public int addUser(User user){
        return userService.addUser(user);
    }

    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize){
        return userService.findAllUser(pageNum,pageSize);
    }
}

最终的文件结构

spring boot 学习笔记

在运行内嵌的service,启动程序

spring boot 学习笔记

在浏览器里面请求测试

测试addUser接口:http://localhost:8080/user/add?username=猪八戒&password=123456&phone=150222222222

测试findAllUser接口:http://localhost:8080/user/all

接口写好了,写api也是个麻烦事,但是有了swagger,那就简单多了!

接下来开始整合swagger2

在pom.xml添加swagger的依赖

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

在application.java同级添加swagger2.java,进行swagger的配置

spring boot 学习笔记

swagger.java

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
                .termsOfServiceUrl("http://blog.didispace.com/")
                .contact("小太阳")
                .version("1.0")
                .build();
    }
}
basePackage("controller的包")

这样配置以后,访问http://localhost:8080/swagger-ui.html就已经可以看到文档了,但是这样的看起来很不友好,可以通过swagger的注解让文档更丰富,更直观

修改UserController.java

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;


    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @ResponseBody
    @PostMapping("/add")
    public int addUser(@RequestBody User user){
        return userService.addUser(user);
    }

    @ApiOperation(value="获取用户列表", notes="")
    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize){
        //开始分页
        return userService.findAllUser(pageNum,pageSize);
    }
}

添加了@ApiOperation 和@ApiImplicitParam两个注解

自己访问api的时候遇到的两个问题。

1.addUser的参数需要使用@RequestBody这样api里面的data type 会有参数模板

2.之前没有加@RequestBody使用的是get请求,加上以后需要使用post请求,主要post请求不能通过浏览器直接访问。

好了,运行项目,访问api接口

spring boot 学习笔记

我们之前写好的两个接口已经显示出来了,点进去可以进行接口测试。

spring boot 学习笔记

添加用户接口成功。

spring boot 学习笔记

用户列表接口也成功了。