基于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地址

相关文章
相关标签/搜索