springboot整合mybatis、Druid、mysql

最近三个多月,利用空闲时间自学java,利用周日休息,心血来潮,做了一个简单项目案例。项目主要用到了springboot、mybatis、druid、mysql技术。废话不多说了,先把建项目过程,贴出来。

新建工程

create_project_1.png

create_project_2.png

create_project_3.png

create_project_4.png

create_project_5.png

create_project_6.png

点击完成按钮,会生成examedemo项目,目录结构如下图所示:


image.png

image.png

新建application.yml文件

application.yml文件配置项


server:
  port: 8082
  undertow:
    io-threads: 15

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/zhixiaole_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
    username: root
    password: root
  druid:
    #监控统计拦截的过滤器 不加监控界面sql无法统计 wall用于防火墙
    filters: stat,wall,log4j,config
    #最大连接数
    max-active: 100
    #初始化大小
    initial-size: 1
    #获取连接最大等待时间
    max-wait: 60000
    min-idle: 1
    #间隔多久检测一次需要关闭的空闲连接 毫秒
    time-between-eviction-runs-millis: 60000
    #连接在连接池中最小生存的时间,毫秒
    min-evictable-idle-time-millis: 300000
    validation-query: select 'x'
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true
    max-open-prepared-statements: 50
    max-pool-prepared-statement-per-connection-size: 20
    web-stat-filter:
      exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      url-pattern: /*
    stat-view-servlet:
      #白名单IP
      allow: 127.0.0.1
      #黑名单IP
      deny: 120.77.85.84
      #登录账号和密码
      login-username: admin
      login-password: admin
      #启用重置数据功能
      reset-enable: true

  thymeleaf:
    prefix: classpath:/templates/
    mode: HTML
    encoding: utf-8
    content-type: text/html
    cache: false


mybatis:
  config-location: classpath:/mybatis/mybatis.cfg.xml
  type-aliases-package: com.examedemo.exame.model
  mapper-locations: classpath*:/mybatis/mapper/*Mapper.xml
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    com.examedemo.exame.mapper : debug

pom.xml文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    

    com.examedemo
    exame
    0.0.1-SNAPSHOT
    exame
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        

        
            com.alibaba
            druid
            1.1.10
        







        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



mybatis.cfg.xml配置文件代码




    
        
        
    

user_weixin

表结构如下

-- ----------------------------
-- Table structure for user_weixin
-- ----------------------------
DROP TABLE IF EXISTS `user_weixin`;
CREATE TABLE `user_weixin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) DEFAULT NULL COMMENT '用户id(只有填写基本资料后才会创建)',
  `nickname` varchar(100) DEFAULT NULL COMMENT '昵称',
  `openid` varchar(100) DEFAULT NULL COMMENT '微信OpenID',
  `unionid` varchar(50) DEFAULT NULL COMMENT 'unionId',
  `sex` int(11) DEFAULT NULL COMMENT '性别',
  `city` varchar(20) DEFAULT NULL COMMENT '所在城市',
  `province` varchar(20) DEFAULT NULL COMMENT '所在省份',
  `country` varchar(20) DEFAULT NULL COMMENT '所在国家',
  `avatar_url` varchar(200) DEFAULT NULL COMMENT '用户头像',
  `reg_time` datetime DEFAULT NULL COMMENT '注册时间',
  `mobile` varchar(12) DEFAULT NULL,
  `snsid` int(11) DEFAULT '0' COMMENT 'bbs系统用户编号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=244 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='微信用户表';

IUserWeixinMapper.xml








    
        
        


    

    

ExameApplication.java

package com.examedemo.exame;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.examedemo.exame.mapper")
public class ExameApplication {

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

}

DruidConfig.java

package com.examedemo.exame.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;
import java.sql.SQLException;


@Configuration
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidServlet(){
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("allow", "127.0.0.1");
        reg.addInitParameter("deny","");
        reg.addInitParameter("loginUsername", "admin");
        reg.addInitParameter("loginPassword", "admin");
        return reg;
    }



    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean(name="dataSource")
    public DataSource druidDataSource(
            @Value("${spring.datasource.driver-class-name}") String driver,
            @Value("${spring.datasource.url}") String url,
            @Value("${spring.datasource.username}") String username,
            @Value("${spring.datasource.password}") String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        try {
            druidDataSource.setFilters("stat, wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }
}

IndexController.java

package com.examedemo.exame.controllers.admin;

import com.examedemo.exame.model.UserWeixinModel;
import com.examedemo.exame.service.impl.UserWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private UserWeixinService userWeixinService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    @ResponseBody
    public String index(){
        return "hello world";
    }


    @ResponseBody
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public List users(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("content-type","application/json");
        return userWeixinService.getList();
    }
}

IUserWeixinMapper.java

package com.examedemo.exame.mapper;


import com.examedemo.exame.model.UserWeixinModel;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


public interface IUserWeixinMapper {

    public List findAll();
}

UserWeixinModel.java

package com.examedemo.exame.model;

import java.io.Serializable;

public class UserWeixinModel implements Serializable {
    private Integer id;
    private Integer userid;
    private String nickname;
    private String openid;
    private Integer sex;
    private String city;
    private String province;
    private String country;
    private String avatarUrl;
    private String regTime;
    private String mobile;
    private Integer snsid;

    public Integer getId() {
        return id;
    }

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

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public long getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getRegTime() {
        return regTime;
    }

    public void setRegTime(String regTime) {
        this.regTime = regTime;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getSnsid() {
        return snsid;
    }

    public void setSnsid(Integer snsid) {
        this.snsid = snsid;
    }
}

IUserWeixinService.java

package com.examedemo.exame.service;

import com.examedemo.exame.model.UserWeixinModel;

import java.util.List;

public interface IUserWeixinService {

    public List getList();
}

UserWeixinService.java

package com.examedemo.exame.service.impl;

import com.examedemo.exame.mapper.IUserWeixinMapper;
import com.examedemo.exame.model.UserWeixinModel;
import com.examedemo.exame.service.IUserWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserWeixinService implements IUserWeixinService {

    @Autowired
    private  IUserWeixinMapper userWeixinMapper;

    public List getList(){
        return userWeixinMapper.findAll();
    }
}

你可能感兴趣的:(springboot整合mybatis、Druid、mysql)