基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架環境搭建

前言

最近做回后臺開發,重新抓起以前學過的SSM(Spring+Spring MVC+Mybatis),但是發現配置實在過于復雜,好多東西配置起來麻煩,雖然最終是配置出來了,但是還是感覺開發速度跟不上,本來打算切換到jfianl,但是后來發現需要用的幾個框架不支持jfianl,如Swagger2(根據代碼中的注解生成接口文檔和測試頁面,非常的方便);同時我也不愿意放棄SpringMVC強大的驗證參數模塊,jfianl中好像只能手動驗證(當然我對jfianl只處于簡單的開發,并不是特別熟),而SpringMVC中,直接就能通過注解來確定哪些參數是必須的,哪些不是必須的,這對于寫接口的人來說,方便了很多,所以決定還是使用Spring家族的東西,下面先一一介紹下本文的主角們

Spring boot

spring-boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Boot致力于在蓬勃發展的快速應用開發領域(rapid application development)成為領導者

多年以來,Spring IO平臺飽受非議的一點就是大量的XML配置以及復雜的依賴管理。在2013年的SpringOne 2GX會議上,Pivotal的CTO Adrian Colyer回應了這些批評,并且特別提到該平臺將來的目標之一就是實現免XML配置的開發體驗。Boot所實現的功能超出了這個任務的描述,開發人員不僅不再需要編寫XML,而且在一些場景中甚至不需要編寫繁瑣的import語句。在對外公開的beta版本剛剛發布之時,Boot描述了如何使用該框架在140個字符內實現可運行的web應用,從而獲得了極大的關注度,該樣例發表在tweet

當然上面又是我抄過來的,因為我覺得要我去介紹一個框架是什么的時候,我只會說我的理解,但是我的理解不能讓大家知道它的背景,所以抄了上面那段,那么下面就是我理解的Spring boot是個什么東西

無需繁瑣配置的Spring集合包 Spring boot本身并不是什么新的框架,它可以說只是Spring大家族的一個集合包,當然這個集合包吧基礎的配置都給我配置好了,我們無需再進行繁瑣的xml配置,甚至是都不用配置web.xml,因為spring boot內部自己集成了一個tomcat,直接通過run的方式就能啟動,打包也一樣,都可以不用部署tomcat了,當然是針對小項目,大項目肯定是要對中間件進行一些優化的

Mybatis

MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或注解用于配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。當然我個人更傾向用注解,因為實在是不怎么喜歡配置xml,尤其是eclipse經常因為xml的一些問題卡主,導致編譯要等xml驗證通過后才能編譯,而我用Mybatis最主要的地方就是因為不用像JDBC那樣自己一個屬性一個屬性來賦值

Druid

Druid是一個JDBC組件,它包括三部分:

DruidDriver 代理Driver,能夠提供基于Filter-Chain模式的插件體系。
DruidDataSource 高效可管理的數據庫連接池。
SQLParser
Druid可以做什么?

  1. 可以監控數據庫訪問性能,Druid內置提供了一個功能強大的StatFilter插件,能夠詳細統計SQL的執行性能,這對于線上分析數據庫訪問性能有幫助。

  2. 替換DBCP和C3P0。Druid提供了一個高效、功能強大、可擴展性好的數據庫連接池。

  3. 數據庫密碼加密。直接把數據庫密碼寫在配置文件中,這是不好的行為,容易導致安全問題。DruidDruiver和DruidDataSource都支持PasswordCallback。

  4. SQL執行日志,Druid提供了不同的LogFilter,能夠支持Common-Logging、Log4j和JdkLog,你可以按需要選擇相應的LogFilter,監控你應用的數據庫訪問情況。

擴展JDBC,如果你要對JDBC層有編程的需求,可以通過Druid提供的Filter-Chain機制,很方便編寫JDBC層的擴展插件。

其實說簡單點Druid就是一個功能強大,性能優秀的數據庫連接池,是由阿里巴巴的大牛們開發的,除了性能好之外,我最喜歡的就是它的監控功能了,連github上的說明都是“為監控而生的數據庫連接池!”

Swagger2

關于Swagger的介紹和非代碼搭建,在之前的文章已經說過了,不過這里的Swagger2只是版本號為2而已,很多核心的東西都沒怎么變化,當然如果不用和代碼封裝在一起,也可以參考Swagger的介紹和非代碼搭建,不過本文主要講述在代碼中集成,所以不再過多描述

mybatis-generator

mybatis-generator是用來根據數據自動生成實體bean和一些常規查詢語句的插件,有了這個就不用再一個一個實體bean來寫了,而且普通的查詢也可以使用自動生成sql語句查詢出來

開始搭建

一、創建項目

首先創建一個maven項目,當然最好創建maven-archetype-webapp,原因無他,主要是因為很多時候我還是需要把項目部署到優化過配置的tomcat獲取其他容器中,當然也可以創建普通的maven項目

二、添加依賴
<!-- Springboot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-aop</artifactId>
        </dependency>
        <!-- Springboot 熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Swagger API文檔 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- druid阿里巴巴數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>
        <!-- MySql數據庫驅動 -->
        <dependency>
            <groupId> mysql</groupId>
            <artifactId> mysql-connector-java</artifactId>
            <version> 5.0.5</version>
        </dependency>

其中spring-boot-devtools不是必須,只是如果你想在運行的時候,修改了代碼能自動更新,而不用手動重啟,就需要加上

三、添加Applcation類

這個就是程序的入口類了,代碼如下

package wang.raye.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;

/**
 * 
 * 
 * @author Raye
 * @since 2016年10月9日22:22:31
 */
@MapperScan("wang.raye.springboot.model.mapper")
@SpringBootApplication
@ServletComponentScan
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);

    }

}

想要運行項目時可以直接運行此類就可以,如你所見,其中有main方法,所以可以直接運行

下面說說3個注解的含義

@MapperScan("wang.raye.springboot.model.mapper"),掃描wang.raye.springboot.model.mapper下面的mapper接口,其中mapper下面的接口是由mybatis-generator自動生成的,會在后面細說,現在就先知道是個什么東西就行了
@SpringBootApplication很多Spring Boot開發者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他們的main類。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實踐時),Spring Boot提供一個方便的 @SpringBootApplication 選擇。該 @SpringBootApplication 注解等價于以默認屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan

@ServletComponentScan有此注解后,項目中如果需要使用java原生的servlet和filter,可以在類中使用注解實現,主要是配置Druid監控時需要用到

四、創建配置文件

雖然spring boot可以不用配置xml,但是也并不是完全不需要配置文件,當然不用配置文件也能跑起來,只是有配置文件我們可以配置很多東西,只是不用像以前xml那么麻煩,首先需要在resource文件夾下面創建application.yml文件


server:
  port: 80
spring:
  application:
    name: admin-managee
  datasource:
    url: jdbc:mysql://192.168.157.133:3306/springboot
    username: raye
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
          max-active: 20
          initial-size: 1
          min-idle: 3
          max-wait: 60000
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 300000
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false

  
debug: true

相信這個文件很容易看懂,首先server:下面的port:80這個是定義了運行的端口,之前說過spring boot內置了tomcat服務器,所以如果要使用內置的tomcat并且不想用8080端口,就需要在這里配置

下面就是datasource的配置,這樣不寫進代碼有個好處,那就是如果是給客戶用的程序,可以很方便的修改數據庫配置,而不用重新編譯,當然如果你是打包jar我估計是要重新編譯的,如果是war,那么就可以解壓出來直接修改application.yml而不用重新編譯了

而debug:true就是說明當時是調試狀態,這樣就會輸出很多log

五、創建Druid數據源配置類
package wang.raye.springboot.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
@Configuration  
@EnableTransactionManagement 
/**
 * Druid的DataResource配置類
 * @author Raye
 * @since 2016年10月7日14:14:18
 */
public class DruidDataSourceConfig  implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;

    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    }
    
    @Bean
    public DataSource dataSource() {
        System.out.println("注入druid?。?!");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver.getProperty("url"));
        datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver.getProperty("username"));
        datasource.setPassword(propertyResolver.getProperty("password"));
        datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
        datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
        datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
        datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
        datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }
}

主要是創建一個druid的DruidDataSource 返回并告訴spring boot這是一個bean

六、創建Druid的監控servlet和filter

創建監控Servlet

package wang.raye.springboot.config;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

import com.alibaba.druid.support.http.StatViewServlet;

/**
 * Druid的Servlet
 * @author Raye
 * @since 2016年10月7日14:13:39
 */
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/druid/*", 
initParams={
        @WebInitParam(name="allow",value="127.0.0.1,192.168.1.126"),// IP白名單 (沒有配置或者為空,則允許所有訪問)
        @WebInitParam(name="deny",value="192.168.1.111"),// IP黑名單 (存在共同時,deny優先于allow)
        @WebInitParam(name="loginUsername",value="Raye"),// 用戶名
        @WebInitParam(name="loginPassword",value="123456"),// 密碼
        @WebInitParam(name="resetEnable",value="false")// 禁用HTML頁面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {


}

@WebServlet表明這是一個Servlet,和之前Application中的@ServletComponentScan相對應使用
創建filter

package wang.raye.springboot.config;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import com.alibaba.druid.support.http.WebStatFilter;

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
    @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略資源
})
/**
 * Druid攔截器,用于查看Druid監控
 * @author Raye
 * @since 2016年10月7日14:59:27
 */
public class DruidStatFilter extends WebStatFilter {

}

同樣@WebFilter表明此類是一個攔截器

創建好之后,我們訪問http://localhost/druid/index.html,會自動跳到http://localhost/druid/login.html登錄頁面,登錄進去會出現以下界面

預覽圖

七、配置mybatis

其實mybatis之前就已經配置好了,就是Application類的@MapperScan("wang.raye.springboot.model.mapper")注解,這個注解說明了要掃描的mybatis的mapper接口包,當然如果是用xml的話應該還需要其他配置,不過我個人并不喜歡用xml的方式,所以也沒有怎么研究

八、配置mybatis-generator

配置MyBatis-generator自動生成實體bean,首先需要在pom.xml中添加相關插件依賴,注:==我是用插件的方式來生成實體bean==的,

<build>
        <finalName>springboot</finalName>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <!--數據庫驅動 -->
                    <dependency>
                        <groupId> mysql</groupId>
                        <artifactId> mysql-connector-java</artifactId>
                        <version> 5.0.5</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis</groupId>
                        <artifactId>mybatis-spring</artifactId>
                        <version>1.2.2</version>
                    </dependency>

                    <dependency>
                        <groupId>org.mybatis</groupId>
                        <artifactId>mybatis</artifactId>
                        <version>3.2.4</version>
                    </dependency>


                </dependencies>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!--允許移動生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆蓋 -->
                    <overwrite>true</overwrite>
                    <!-- 自動生成的配置 -->
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>

    </build>

其中除了<finalName>springboot</finalName>是pom.xml默認的節點外,其他都是配置Mybatis-generator的,當然還有頂部的

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <entity.target.dir>src/main/java/</entity.target.dir>
    <dao.resources.dir>src/main/resources/</dao.resources.dir>
</properties>

這個是用來在mybatis-generator.xml中需要使用的

下面開始配置mybatis-generator.xml
首先在resource文件夾下面創建mybatis-generator.xml文件,然后添加如下配置

<?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>

    <context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat">
        <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
            <property name="searchString" value="[e|E]xample$" />
            <property name="replaceString" value="Criteria" />
        </plugin>

    <commentGenerator>
        <property name="suppressDate" value="true" />
    </commentGenerator>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://192.168.157.133:3306/springboot" userId="root"
        password="1993316">
    </jdbcConnection>

    <javaTypeResolver>
        <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- generate Model -->
    <javaModelGenerator targetPackage="wang.raye.springboot.model"
        targetProject="${entity.target.dir}">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
    </javaModelGenerator>



    <!-- 自動生成xml(但是好像一直沒有生成功,反正也不用xml) -->
    <sqlMapGenerator  targetPackage="wang.raye.springboot.model.mapper"
        targetProject="${dao.resources.dir}">
        <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- 自動生成mapper接口, 可以是 ANNOTATEDMAPPER(注解), XMLMAPPER(xml), MIXEDMAPPER(不知道) -->
    <javaClientGenerator type="ANNOTATEDMAPPER"
        targetPackage="wang.raye.springboot.model.mapper" implementationPackage="wang.raye.springboot.model.mapper.impl"
        targetProject="${entity.target.dir}">
        <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <table tableName="user" domainObjectName="User" ></table>
    </context>
</generatorConfiguration>  

其實需要自己修改數據庫配置,因為插件不會讀取spring boot中的數據庫配置,所以需要在mybatis-generator.xml中配置好數據庫,同時也需要修改自己的包名

table節點中的tableName是指在數據庫中的表名,domainObjectName是只生成的實體bean的類名,當然domainObjectName可以不用配置,會默認生成,當然如果有特殊需要可以配置

配置Swagger2
package wang.raye.springboot;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import wang.raye.springboot.model.User;

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 可以定義多個組,比如本類中定義把test和demo區分開了 (訪問頁面就可以看到效果了)
     *
     */
    @Bean
    public Docket testApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("wang.raye.springboot"))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo("SpringBoot學習demo", // 大標題
                "Spring boot + swagger + mybatis + druid", // 小標題
                "1.0", // 版本
                "NO terms of service", "admin@raye.wang", // 作者
                "RayeBlog", // 鏈接顯示文字
                "http://www.raye.wang/"http:// 網站鏈接
        );

        return apiInfo;
    }
}

相信看代碼很容易看懂,我就不多說了

編寫demo

至此,環境配置都配置好了,然后我創建一個簡單的接口來添加用戶,首先看看我的表結構

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `psw` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

因為只是做演示,所以非常簡單,然后看我生成的User.java

package wang.raye.springboot.model;

public class User {

    private Integer id;

    private String username;
    private String psw;

    public Integer getId() {
        return id;
    }


    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPsw() {
        return psw;
    }

    public void setPsw(String psw) {
        this.psw = psw == null ? null : psw.trim();
    }
}

當然我是刪除了很多自動生成的注釋,因為看著太煩,不適合在博客上展示,然后看看UserMapper.java

package wang.raye.springboot.model.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
import wang.raye.springboot.model.User;
import wang.raye.springboot.model.UserCriteria;

public interface UserMapper {

    @SelectProvider(type=UserSqlProvider.class, method="countByExample")
    long countByExample(UserCriteria example);

    @DeleteProvider(type=UserSqlProvider.class, method="deleteByExample")
    int deleteByExample(UserCriteria example);

    @Delete({
        "delete from user",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer id);

    @Insert({
        "insert into user (id, username, ",
        "psw)",
        "values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, ",
        "#{psw,jdbcType=VARCHAR})"
    })
    int insert(User record);

    @InsertProvider(type=UserSqlProvider.class, method="insertSelective")
    int insertSelective(User record);

    @SelectProvider(type=UserSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
        @Result(column="psw", property="psw", jdbcType=JdbcType.VARCHAR)
    })
    List<User> selectByExample(UserCriteria example);

    @Select({
        "select",
        "id, username, psw",
        "from user",
        "where id = #{id,jdbcType=INTEGER}"
    })
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
        @Result(column="psw", property="psw", jdbcType=JdbcType.VARCHAR)
    })
    User selectByPrimaryKey(Integer id);


    @UpdateProvider(type=UserSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") User record, @Param("example") UserCriteria example);


    @UpdateProvider(type=UserSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") User record, @Param("example") UserCriteria example);


    @UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(User record);

    @Update({
        "update user",
        "set username = #{username,jdbcType=VARCHAR},",
          "psw = #{psw,jdbcType=VARCHAR}",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(User record);
}

同樣刪除了注釋,當然還會自動生成UserCriteria.java 和UserSqlProvider,這2個類主要用于模板查詢,用過myBatis應該都知道,就不貼出來了,主要是我們的demo中也不會用到

一、創建UserServer接口
package wang.raye.springboot.server;

import java.util.List;

import wang.raye.springboot.model.User;

/**
 * 用戶服務
 * @author Raye
 * @since 2016年9月21日20:57:39
 */
public interface UserServer {
    /**
     * 添加一個用戶
     * @param user 用戶對象
     * @since 2016年9月21日20:58:17
     * @return 是否添加成功
     */
    public boolean add(User user);
}

二、創建UserServerImpl
package wang.raye.springboot.server.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import wang.raye.springboot.model.User;
import wang.raye.springboot.model.mapper.UserMapper;
import wang.raye.springboot.server.UserServer;
/**
 * 用戶相關數據庫操作實現類
 * @author Raye
 * @since 2016年10月11日19:29:02
 */
@Repository
public class UserServerImpl implements UserServer {
    @Autowired
    private UserMapper mapper;
    
    public boolean add(User user) {
        return mapper.insert(user) > 0;
    }

    public List<User> findAll() {
        return mapper.selectByExample(null);
    }

}
三、創建UserController
package wang.raye.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import wang.raye.springboot.model.User;
import wang.raye.springboot.server.UserServer;

@Api(value="用戶相關的接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer server;
    /**
     * 添加用戶
     * @param user 用戶對象
     * @since 2016年9月21日21:01:50
     */
    @RequestMapping("/add")
    @ApiOperation(notes="添加用戶",value="添加一個用戶",httpMethod="POST")
    
    @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    public String add(@RequestBody User user){
        return "hello "+server.add(user);
    }
}

到此一個接口就完成了,我們可以到swagger2的文件頁面去測試http://localhost/swagger-ui.htm 注意如果端口不是80需要加上端口號,點開頁面中的用戶相關的接口 和GET /user/add可以看到如下頁面

swagger預覽圖

我們可以在parameters處輸入

{
  "psw": "Raye",
  "username": "123456"
}

點擊try it out就可以測試了,當然你也可能不想用json的方式,可以使用

@ApiImplicitParams({
    @ApiImplicitParam(name="username",paramType="query",dataType="string"),
    @ApiImplicitParam(name="psw",paramType="query",dataType="string")
})

代替

@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")

同時為了隱藏user參數,需要在SwaggerConfig類的testApi方法中添加.ignoredParameterTypes(User.class)

    @Bean
    public Docket testApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .ignoredParameterTypes(User.class)
                .select()
                .apis(RequestHandlerSelectors.basePackage("wang.raye.springboot"))
                .paths(PathSelectors.any()).build();
    }

測試界面就會變為


swagger2預覽圖

結尾

好了,到這里一個Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架環境就搭建完成了,歡迎大家留言交流,另外附上本項目

demo oschina地址

demo github地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,958評論 6 342
  • 前言 最近做新項目,正好借這個機會把項目架構整體翻新一遍。整體上最大的變化在于Spring-boot。用到的框架包...
    小強你怎么了閱讀 3,230評論 1 8
  • 人們都說天空是倒過來的海洋 就這樣 在低頭看手機的時候 在面對一大堆數字瘋狂計算的時候 在圖書館背題的時候 突然抬...
    梁意Athena閱讀 622評論 0 6
  • 今天晚上看了6頻道很接地氣的一個節目,叫老娘舅?有一個調解是在杭州打工的一對夫妻吵架了,原因與此文無關(也是我忘了...
    大花SANG閱讀 271評論 0 0