SpingBoot(四)——整合Mybatis(druid连接池)

代码环境

jdk                          1.8 
IDE                          IDEA2007
Springboot              2.1.3.RELEASE     
  1. ​ 新建SpringBoot项目导入场景启动器和所需jar

      <!--SpringBoot版本号2.1.3.RELEASE-->
    <parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.1.3.RELEASE</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    
    
    
    
    <dependencies>
    		<!--SpringBoot默认不支持jsp官方推荐thymeleaf模板引擎-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-thymeleaf</artifactId>
    		</dependency>
    		<!--web核心模块-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<!--mybatis场景启动器-->
    		<dependency>
    			<groupId>org.mybatis.spring.boot</groupId>
    			<artifactId>mybatis-spring-boot-starter</artifactId>
    			<version>2.0.0</version>
    		</dependency>
    		<!--mysql驱动-->
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<scope>runtime</scope>
    		</dependency>
    		<!-- 阿里druid连接池强大好用 -->
    		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>druid-spring-boot-starter</artifactId>
    			<version>1.1.10</version>
    		</dependency>
    		<!--插件一非必须-->
    		<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-configuration-processor</artifactId>
    			<optional>true</optional>
    		</dependency>
    		<!--插件二非必须-->
    		<!--在实体类上使用@Data 就不用再手动生成get/set方法-->
    		<dependency>
    			<groupId>org.projectlombok</groupId>
    			<artifactId>lombok</artifactId>
    			<optional>true</optional>
    		</dependency>
    		<!--测试场景-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    	</dependencies>
    
  2. 配置数据源

    server:
      port: 8081
    spring:
      datasource:
        username: root 
        password: root
        url: jdbc:mysql://192.168.1.11:3306/springboot?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
        druid:
          #初始化大小
          initial-size: 5
          #最大
          min-idle: 5
          #最小
          max-active: 20
          #最大超时时间
          max-wait: 60000
          #配置检测时间 关闭空闲连接
          time-between-eviction-runs-millis: 6000
          #配置单个连接最小生存时间
          min-evictable-idle-time-millis: 300000
          #验证数据库连接语句
          validation-query: SELECT 1
          #建议配置为true,不影响性能,并且保证安全性。
          #申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
          test-while-idle: true
          #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
          test-on-borrow: false
          #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
          test-on-return: false
          # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
          filters: stat,wall,slf4j
          #SQL最慢监控
          filter:
            stat:
              log-slow-sql: true
        #配置Date返回类型的格式;不用再在web页面上进行转换      
      jackson:
        date-format: yyyy-MM-dd HH:mm:ss
        #mybatis配置
    mybatis:
       #配置xml文件位置
      mapper-locations: classpath:mapper/*.xml
      #开启驼峰命名
      configuration:
        map-underscore-to-camel-case: true
    
  3. 开启dao层扫描

    @MapperScan("com.springboot.mybatis.dao") //配置dao层的扫描文件
    @SpringBootApplication
    public class SpringBootIntegrationMybatisApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpringBootIntegrationMybatisApplication.class, args);
    	}
    
    }
    
  4. 代码编写 配置druid的servlet

    package com.springboot.mybatis.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    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.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     *阿里连接池   http://localhost:8081/druid        web地址
     */
    @Configuration
    public class DruidConfig {
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druid(){
            return new DruidDataSource();
        }
    
        //配置管理后台的servlet 即阿里druid中sql的监控页面不能用springboot内置servlet启动
        @Bean
        public ServletRegistrationBean setViewServlet(){
            ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
            Map<String,String> initParams=new HashMap<>();
            initParams.put("loginUsername","admin"); //登录名称
            initParams.put("loginPassword","123456"); //密码
            initParams.put("allow","127.0.0.1");//白名单
            initParams.put("deny","");//黑名单
            bean.setInitParameters(initParams);
            return bean;
        }
        //配置web监控的filter
        @Bean
        public FilterRegistrationBean webStatFiler(){
            FilterRegistrationBean bean=new FilterRegistrationBean();
            bean.setFilter(new WebStatFilter());
            Map<String,String> initParams=new HashMap<>();
            initParams.put("exclusions","*.js,*.css,/druid/*,/static/**");
            bean.setInitParameters(initParams);
            bean.setUrlPatterns(Arrays.asList("/*"));
            return  bean;
        }
    }
    
    

    5.编写controller/dao/service代码及SQL
    GitHub项目地址

上一篇:SpingBoot三——基础架构


下一篇:科研提升实训(0)——开题