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

前言

最近作回後臺開發,從新抓起之前學過的SSM(Spring+Spring MVC+Mybatis),可是發現配置實在過於複雜,好多東西配置起來麻煩,雖然最終是配置出來了,可是仍是感受開發速度跟不上,原本打算切換到jfianl,可是後來發現須要用的幾個框架不支持jfianl,如Swagger2(根據代碼中的註解生成接口文檔和測試頁面,很是的方便);同時我也不肯意放棄SpringMVC強大的驗證參數模塊,jfianl中好像只能手動驗證(固然我對jfianl只處於簡單的開發,並非特別熟),而SpringMVC中,直接就能經過註解來肯定哪些參數是必須的,哪些不是必須的,這對於寫接口的人來講,方便了不少,因此決定仍是使用Spring家族的東西,下面先一一介紹下本文的主角們css

Spring boothtml

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

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

固然上面又是我抄過來的,由於我以爲要我去介紹一個框架是什麼的時候,我只會說個人理解,可是個人理解不能讓你們知道它的背景,因此抄了上面那段,那麼下面就是我理解的Spring boot是個什麼東西git

無需繁瑣配置的Spring集合包 Spring boot自己並非什麼新的框架,它能夠說只是Spring你們族的一個集合包,固然這個集合包吧基礎的配置都給我配置好了,咱們無需再進行繁瑣的xml配置,甚至是都不用配置web.xml,由於spring boot內部本身集成了一個tomcat,直接經過run的方式就能啓動,打包也同樣,均可以不用部署tomcat了,固然是針對小項目,大項目確定是要對中間件進行一些優化的github

Mybatisweb

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

Druidsql

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語句查詢出來

開始搭建

1、建立項目

首先建立一個maven項目,固然最好建立maven-archetype-webapp,緣由無他,主要是由於不少時候我仍是須要把項目部署到優化過配置的tomcat獲取其餘容器中,固然也能夠建立普通的maven項目

2、添加依賴

XML

<!-- 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不是必須,只是若是你想在運行的時候,修改了代碼能自動更新,而不用手動重啓,就須要加上

3、添加Applcation類

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

Java

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監控時須要用到

4、建立配置文件

雖然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

5、建立Druid數據源配置類

Java

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

6、建立Druid的監控servlet和filter

建立監控Servlet

Java

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

Java

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登陸頁面,登陸進去會出現如下界面 預覽圖

7、配置mybatis

其實mybatis以前就已經配置好了,就是Application類的@MapperScan("wang.raye.springboot.model.mapper")註解,這個註解說明了要掃描的mybatis的mapper接口包,固然若是是用xml的話應該還須要其餘配置,不過我我的並不喜歡用xml的方式,因此也沒有怎麼研究

8、配置mybatis-generator

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

XML

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

其中除了springboot是pom.xml默認的節點外,其餘都是配置Mybatis-generator的,固然還有頂部的

XML

<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

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

Java

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/"// 網站連接
        );

        return apiInfo;
    }
}

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

編寫demo

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

SQL

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

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

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中也不會用到

1、建立UserServer接口

Java

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);
}

2、建立UserServerImpl

Java

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);
    }

}

3、建立UserController

Java

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處輸入

JSON

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

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

Java

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

代替

Java

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

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

Java

@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地址

相關文章
相關標籤/搜索