(A02)Spring Boot項目整合mybatis、swagger

SpringBoot整合mybatis、swagger

創建springboot項目步驟在這裏就不說了,可參考IDEA創建Spring Boot項目

1、準備數據庫及表,一個sec_user如下

CREATE TABLE `sec_user` (
  `user_id` varchar(36) NOT NULL COMMENT '用戶id',
  `username` varchar(40) DEFAULT NULL COMMENT '用戶名',
  `password` varchar(40) DEFAULT NULL COMMENT '登錄密碼',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='用戶信息表';


2、添加mybatis依賴

<!-- mysql依賴 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- alibaba的druid數據庫連接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<!-- 其他工具依賴 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.35</version>
</dependency>

3、配置Druid數據源

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperty {
    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private int initialSize;
    private int minIdle;
    private int maxActive;
    private int maxWait;
    private int timeBetweenEvictionRunsMillis;
    private int minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private String filters;/// set get略
/**
 * 數據庫連接池
 */
@Configuration
public class DruidConfig {

    @Autowired
    DruidProperty druidProperty;
    @Bean
    @Primary //在同樣的DataSource中,首先使用被標註的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidProperty.getUrl());
        datasource.setUsername(druidProperty.getUsername());
        datasource.setPassword(druidProperty.getPassword());
        datasource.setDriverClassName(druidProperty.getDriverClassName());
        datasource.setInitialSize(druidProperty.getInitialSize());
        datasource.setMinIdle(druidProperty.getMinIdle());
        datasource.setMaxActive(druidProperty.getMaxActive());
        datasource.setMaxWait(druidProperty.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(druidProperty.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidProperty.getTimeBetweenEvictionRunsMillis());
        datasource.setValidationQuery(druidProperty.getValidationQuery());
        datasource.setTestOnBorrow(druidProperty.isTestOnBorrow());
        datasource.setTestOnReturn(druidProperty.isTestOnBorrow());
        datasource.setPoolPreparedStatements(druidProperty.isPoolPreparedStatements());
        List filterList=new ArrayList<>();
        filterList.add(wallFilter());
        datasource.setProxyFilters(filterList);
        try {
            datasource.setFilters(druidProperty.getFilters());
        } catch (SQLException e) {
            //logger.info("druid configuration initialization fail: " + ExceptionUtils.getFullStackTrace(e));
        }
        return datasource;
    }

    @Bean
    public ServletRegistrationBean statViewServlet() {
        //創建servlet註冊實體
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //設置ip白名單,默認所有白名單
        servletRegistrationBean.addInitParameter("allow", "");
        //設置ip黑名單
        //servletRegistrationBean.addInitParameter("deny", "192.168.3.31");
        //設置控制檯管理用戶__登錄用戶名和密碼
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin123");
        //是否可以重置數據
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter() {
        //創建過濾器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //設置過濾器過濾路徑
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略過濾的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}

4、修改配置文件application.xml

 

server:
  port: 8080

spring:
  application:
    name: springboot-test
  devtools:
    restart:
      enabled: true
  ## Druid mysql##
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test123?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=true&userAffectRows=true
    username: root
    password: root
    initial-size: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
  output:
    ansi:
      enabled: detect

# mybatis
mybatis:
  mapper-locations: classpath:mapper/**/**.xml
  type-aliases-package: com.cx.model
  configuration:
    map-underscore-to-camel-case: true
    call-setters-on-nulls: true

5、 編寫model實體、maper、service、controller以及修改啓動類

SecUserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cx.mapper.common.SecUserMapper" >
  <resultMap id="BaseResultMap" type="com.cx.model.SecUser" >
    <id column="user_id" property="userId" jdbcType="VARCHAR" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>
  <select id="selectList" resultMap="BaseResultMap">
    select * from sec_user
  </select>

</mapper>

SecUser.java

public class SecUser {
    private String userId;
    private String username;

    private String password;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
}

 SecUserMapper.java

public interface SecUserMapper {
    List<SecUser> selectList();

}  

SecUserService.java

@Service
public class SecUserServiceImpl implements SecUserService {
    @Autowired
    SecUserMapper secUserMapper;

    @Override
    public List<SecUser> listUser() {
        return secUserMapper.selectList();
    }
}

SecUserController.java

@RestController // 等於@Controller+@ResponseBody
@RequestMapping("/user")
public class SecUserController {

    @Autowired
    SecUserService secUserService;

    @GetMapping("/queryUserList")
    public List<SecUser>  queryUserList() {
        List<SecUser> list =  secUserService.listUser();
        return list;
    }
}
啓動類SpringbootTestApplication
@MapperScan("com.cx.mapper")
@SpringBootApplication
public class SpringbootTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTestApplication.class, args);
    }

}

 6、啓動測試

7、整合swagger,添加依賴

<!-- swagger依賴-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

8 、添加swagger配置文件、往controller類添加註解 

// 配置文件Swagger2Config 
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
     public Docket createRestApi() {
         return new Docket(DocumentationType.SWAGGER_2)
                 .apiInfo(apiInfo())
                 .select()
                 .apis(RequestHandlerSelectors.basePackage("com.cx.controller"))
                 .paths(PathSelectors.any())
                 .build();
     }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot項目")
                .description("project description")
                .termsOfServiceUrl("")
                .contact("developer")
                .version("1.0")
                .build();
    }

}

 // 給controller類及方法加上註解

@Api(tags = {"用戶信息API"})
@RestController // 等於@Controller+@ResponseBody
@RequestMapping("/user")
public class SecUserController {

    @Autowired
    SecUserService secUserService;

    @ApiOperation(value = "查詢用戶所有數據", notes = "查詢用戶所有數據")
    @GetMapping("/queryUserList")
    public List<SecUser>  queryUserList() {
        List<SecUser> list =  secUserService.listUser();
        return list;
    }
}

9、啓動訪問測試

訪問http://localhost:8080/swagger-ui.html

也可以加swagger-bootstrap-ui依賴

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.7</version>
</dependency>

 然後訪問http://localhost:8080/doc.html也行

10、最後附上項目截圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章