preface

Recently, I went back to background development and picked up SSM(Spring+Spring MVC+Mybatis) I had learned before, but I found that the configuration was too complicated and it was difficult to configure many things. Although the configuration was finally completed, I still felt that the development speed could not keep up with it. I planned to switch to JFIANL. But it turns out that several frameworks you need to use don’t support JFIanL, such as Swagger2 (which makes it very convenient to generate interface documents and test pages from annotations in code); I also don’t want to give up SpringMVC’s powerful validation parameter module. Jfianl seems to have to be validated manually (although I’m not familiar with Jfianl because I’m in simple development), whereas SpringMVC allows you to determine which parameters are required and which are not. This is a lot easier for interface writers, so I decided to stick with the Spring family. Here are the main characters in this article

Spring boot

Spring-boot is a new framework provided by the Pivotal team, designed to simplify the initial setup and development of new Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations. In this way, Boot aims to be a leader in the burgeoning field of rapid Application development

Over the years, the Spring IO platform has been criticized for its heavy XML configuration and complex dependency management. At the SpringOne 2GX conference in 2013, Adrian Colyer, CTO of Pivotal, addressed these criticisms, noting that one of the future goals of the platform is an XML-free development experience. Boot goes beyond the description of this task, and not only do developers no longer need to write XML, but in some scenarios, they don’t even need to write tedious import statements. When the public beta was released, Boot got a lot of attention by describing how to use the framework to implement a working Web application in 140 characters

Of course, I copied it from above again, because I thought that when I was asked to introduce what a framework is, I would only say my understanding, but my understanding can not let everyone know its background, so I copied the above paragraph, so the following is my understanding of Spring Boot is what

Spring Boot itself is not a new framework, it can be said that it is just a collection of Spring family package, of course, the basic configuration of the package is configured for me, we do not need to do tedious XML configuration, or even web. Because Spring Boot integrates a Tomcat, it can be started directly through the run mode, and packaging is the same, there is no need to deploy Tomcat, of course, for small projects, large projects must be some optimization of the middleware

Mybatis

MyBatis is an excellent persistence layer framework that supports ordinary SQL queries, stored procedures, and advanced mapping. MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval encapsulation of result sets. MyBatis can use simple XML or annotations for configuration and raw mapping to map interfaces and Java’s POJOs (Plain Old Java Objects) to records in the database. Of course, I personally prefer to use annotations, because I really don’t like to configure XML, especially eclipse often due to some problems with XML, resulting in the compilation must wait for XML validation to compile, and the main reason why I use Mybatis is because I don’t need to assign values to one attribute by one attribute like JDBC

Druid

Druid is a JDBC component that has three parts:

DruidDriver Agent Driver that provides filter-chain-based plug-in architecture. DruidDataSource efficiently manages the database connection pool. What does SQLParser Druid do?

Druid provides a powerful StatFilter plugin to monitor the performance of database access. StatFilter allows you to monitor the performance of database access online.

2) Replace DBCP and C3P0. Druid provides an efficient, powerful, and scalable database connection pool.

3) Database password encryption. Writing the database password directly into the configuration file is a bad behavior and may cause security problems. DruidDruiver and DruidDataSource both support PasswordCallback.

Druid provides a variety of logfilters that support common-logging, Log4j, and JdkLog. You can select the appropriate LogFilter to monitor your application’s database access.

If you have programming requirements for the JDBC layer, you can easily write extensions to the JDBC layer using the Filter-chain mechanism provided by Druid.

In fact, simple point Druid is a powerful, excellent performance of the database connection pool, is developed by alibaba’s big cattle, in addition to good performance, my favorite is its monitoring function, even the description on Github is “to monitor the database connection pool!”

Swagger2

Introductions of Swagger and non code set, in the previous article’ve said, but the Swagger2 here is just the version number is 2, how many core things didn’t change, of course if it’s not with the code package, can also refer to Swagger is introduced and the code, but this article focuses on the integration in the code, So no more description

mybatis-generator

Mybatis -Generator mybatis-generator is a plug-in that automatically generates entity beans and regular query statements based on data. With this plug-in, you do not need to write entity beans one by one, and ordinary queries can also be queried using automatic generated SQL statements

Begin to build

Create a project

First, create a Maven project, preferably maven-archetype-webApp, for no other reason, mainly because most of the time I still need to deploy the project to another optimized Tomcat container, as well as create a regular Maven project

Add dependencies
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-aop org.springframework.boot spring-boot-devtools true io.springfox Springfox-swagger - UI 2.2.2 IO. Springfox springfox-Swagger2 2.2.2 org.mybatis. Spring. Boot mybatis-spring-boot-starter Alibaba druid 1.0.26 mysql mysql-connector-java 5.0.5Copy the code

Spring-boot-devtools is not required, but is required if you want to update the code automatically at runtime without having to manually restart it

Add the Applcation class

This is the entry class of the program, the code is as follows

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 October 9, 2016 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); }}Copy the code

You can run this class directly if you want to run your project, and as you can see, it has the main method, so you can run it directly

Here’s what these three notes mean

@ MapperScan (” wang. Raye. Springboot. Model. The mapper “), and scanning wang. Raye. Springboot. Model. Under the mapper mapper interfaces, The mapper interface is automatically generated by mybatis-generator, which will be discussed later. @springBootApplication Many SpringBoot developers always use @Configuration. @enableAutoConfiguration and @ComponentScan annotate their main class. Because these annotations are used together so often (especially if you follow the best practices above), SpringBoot provides a convenient @SpringBootApplication option. The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with the default properties

ServletComponentScan @ServletComponentScan If you want to use native Servlets and Filters in your project, you can use annotations in your classes

4. Create a configuration file

Spring Boot can be configured without XML, but it doesn’t need a configuration file at all. It can run without a configuration file, but with a configuration file you can configure a lot of things, just without the hassle of XML. You first need to create the application.yml file under the Resource folder

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: trueCopy the code

Spring Boot has a built-in Tomcat server, so if you want to use the built-in Tomcat server and don’t want to use port 8080, you need to configure it here

The datasource configuration can be easily modified without having to recompile it. If you want to package a JAR, you will need to recompile it. If you want to recompile a jar, you will need to recompile it. You can then unzip it and directly modify application.yml without recompiling it

Debug: true indicates that the system is in debug mode, which will output many logs

Create the Druid data source configuration class
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 Configuration class * * * * @ author Raye * @ since October 7, 2016 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; }}Copy the code

Basically, the Druid datasource that creates a Druid returns and tells Spring Boot that it is a bean

Create monitor servlets and filters for Druid

Create monitor Servlet

package wang.raye.springboot.config; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import com.alibaba.druid.support.http.StatViewServlet; /** * Druid's Servlet * @author Raye * @since October 7, 2016 14:13:39 */ @SuppressWarnings(" Serial ") @webServlet (urlPatterns = "/druid/*", initParams={@webinitParam (name="allow",value="127.0.0.1,192.168.1.126"),// IP whitelist (not configured or empty, @webinitParam (name="deny",value="192.168.1.111"),// IP blacklist (if common, Deny takes precedence over allow) @webinitParam (name="loginUsername",value="Raye"),// Username @ WebInitParam (name = "loginPassword", value = "123456"), / / password @ WebInitParam (name = "resetEnable", value = "false") / / }) public class DruidStatViewServlet extends StatViewServlet {}Copy the code

@webServlet indicates that this is a Servlet, and [email protected] creates a 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 / *") / / ignore resources}) / * * * Druid interceptor, * @author Raye * @since 2016年10月7 14:59:27 */ Public class DruidStatFilter extends WebStatFilter {}Copy the code

Also, @webFilter indicates that this class is an interceptor

Once created, we accesshttp://localhost/druid/index.html, will automatically jump to the login page, http://localhost/druid/login.html login into the following interface will appear

7. Configure Mybatis

Before actually mybatis is configured, which is the Application class @ MapperScan (” wang. Raye. Springboot. Model. The mapper “) annotations, the annotations shows to scan the mybatis mapper interface package, Of course, if you’re using XML you might need some other configuration, but I personally don’t like XML, so I didn’t do much research. Okay

Configure mybatis- Generator

To configure MyBatis-generator to automatically generate entity beans, you need to add the dependency of the plugin to the pop.xml file.

Springboot org.mybatis. Generator mybatis-generator-maven-plugin 1.3.5 mysql mysql-connector- Java 5.0.5 org.mybatis Mybatis 3.2.4 Generate Mybatis Artifacts package Generate true true SRC/main/resources/mybatis - generator. XML maven - compiler - plugin utf-8 1.5 1.5Copy the code

Except for SpringBoot, which is the default pom. XML node, all the others are configured with Mybatis -Generator, and of course the top one

  
    UTF-8
    src/main/java/
    src/main/resources/
  
Copy the code

This is for use in mybatis-generator.xml

To configure mybatis-generator. XML, first create the mybatis-generator. XML file under the Resource folder and then add the following configuration

  




    
        
            
            
        

    
        
    

    
    

    
        
    

    
    
        
        
    



    
    
        
    

    
    
        
    

    
      
Copy the code

You will need to modify the database configuration yourself, as the plugin will not read the database configuration in Spring Boot, so you will need to configure the database in mybatis-generator.xml, and you will also need to change your package name

The tableName in the table node refers to the name of the table in the database, and the domainObjectName is the class name of the entity bean that is only generated. Of course, the domainObjectName can not be configured. It will be generated by default

Configuration 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 {/** * Such as the classes defined in separate test and demo (access page can see the effect) * * / @ 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 learning demo", Spring Boot + Swagger + mybatis + druid", "NO terms of service"[email protected]", / / the author RayeBlog, / / link displays text "http://www.raye.wang/" / / website link); return apiInfo; }}Copy the code

I’m sure it’s easy to read the code, so I won’t go into that

Write the demo

Now that the environment configuration is configured, I create a simple interface to add users, starting with my table structure

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;
Copy the code

It’s very simple because it’s just a demonstration, and then look at the user.java that I generated

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(); }}Copy the code

Of course I removed a lot of the auto-generated comments because they were too annoying to show on my blog, and then look at 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 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);
}
Copy the code

Also deleted comments, of course, will automatically generate UserCriteria. Java and UserSqlProvider, these two classes are mainly used for template query, used myBatis should know, will not post out, mainly is our demo will not use

Create the UserServer interface
package wang.raye.springboot.server; import java.util.List; import wang.raye.springboot.model.User; Public interface UserServer {/** * add a user * @param user object */ ** * Add a user * @param user object */ ** * Add a user * @param user object */ */ public Boolean add(User User); */ public Boolean add(User User); }Copy the code
Create 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 * @author Raye * @@repository public class UserServerImpl implements UserServer { @Autowired private UserMapper mapper; public boolean add(User user) { return mapper.insert(user) > 0; } public List findAll() { return mapper.selectByExample(null); }}Copy the code
Create 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=" user related interface ") @restController @RequestMapping("/user") Public Class UserController {@autoWired private UserServer server; /** * add user * @param user * @requestMapping ("/add") @apiOperation (notes=" add user", value=" add user", httpMethod="POST") @apiImplICITParam (name =" user", value=" user detail entity user", required = true, dataType = "User") public String add(@RequestBody User user){ return "hello "+server.add(user); }}Copy the code

This interface is complete, we can go to swagger2 file page to testhttp://localhost/swagger-ui.htmNotice If the port number is not 80, you need to add the port number. Click user-related interfaces and GET /user/add to view the following pageWe can enter it in parameters

{
  "psw": "Raye",
  "username": "123456"
}
Copy the code

You can test it by hitting Try it out, or you don’t want to use JSON, you can use json

@ApiImplicitParams({
    @ApiImplicitParam(name="username",paramType="query",dataType="string"),
    @ApiImplicitParam(name="psw",paramType="query",dataType="string")
})
Copy the code
@APIIMPLICITParam (name = "user", value = "user detail entity user", Required = true, dataType = "user")Copy the code

IgnoredParameterTypes (user.class) to hide the user parameter, add it to testApi method of SwaggerConfig 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();
    }
Copy the code

The test screen will become

At the end

Springboot+Mybatis+Druid+Swagger2+ Mybatis – Generator framework environment is completed

The demo oschina address

The demo making address