springboot配置数据库连接池druid
新建springboot项目
druid学习地址
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
所需pom依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <parent> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-parent</artifactId> 8 <version>2.2.1.RELEASE</version> 9 <relativePath/> <!-- lookup parent from repository --> 10 </parent> 11 <groupId>com.javaqi</groupId> 12 <artifactId>springboot002</artifactId> 13 <version>0.0.1-SNAPSHOT</version> 14 <name>springboot002</name> 15 <description>Demo project for Spring Boot</description> 16 17 <properties> 18 <java.version>1.8</java.version> 19 <mysql.version>5.1.44</mysql.version> 20 </properties> 21 22 <dependencies> 23 <dependency> 24 <groupId>org.springframework.boot</groupId> 25 <artifactId>spring-boot-starter-jdbc</artifactId> 26 </dependency> 27 <dependency> 28 <groupId>org.springframework.boot</groupId> 29 <artifactId>spring-boot-starter-thymeleaf</artifactId> 30 </dependency> 31 <dependency> 32 <groupId>org.springframework.boot</groupId> 33 <artifactId>spring-boot-starter-web</artifactId> 34 </dependency> 35 <dependency> 36 <groupId>org.mybatis.spring.boot</groupId> 37 <artifactId>mybatis-spring-boot-starter</artifactId> 38 <version>2.1.1</version> 39 </dependency> 40 41 <dependency> 42 <groupId>mysql</groupId> 43 <artifactId>mysql-connector-java</artifactId> 44 <version>${mysql.version}</version> 45 <scope>runtime</scope> 46 </dependency> 47 <dependency> 48 <groupId>org.projectlombok</groupId> 49 <artifactId>lombok</artifactId> 50 <optional>true</optional> 51 </dependency> 52 <dependency> 53 <groupId>org.springframework.boot</groupId> 54 <artifactId>spring-boot-starter-test</artifactId> 55 <scope>test</scope> 56 <exclusions> 57 <exclusion> 58 <groupId>org.junit.vintage</groupId> 59 <artifactId>junit-vintage-engine</artifactId> 60 </exclusion> 61 </exclusions> 62 </dependency> 63 64 <dependency> 65 <groupId>com.alibaba</groupId> 66 <artifactId>druid-spring-boot-starter</artifactId> 67 <version>1.1.10</version> 68 </dependency> 69 <dependency> 70 <groupId>org.springframework</groupId> 71 <artifactId>spring-aspects</artifactId> 72 </dependency> 73 74 <dependency> 75 <groupId>com.github.pagehelper</groupId> 76 <artifactId>pagehelper-spring-boot-starter</artifactId> 77 <version>1.2.3</version> 78 </dependency> 79 80 </dependencies> 81 82 <build> 83 <resources> 84 <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> 85 <resource> 86 <directory>src/main/java</directory> 87 <includes> 88 <include>**/*.xml</include> 89 </includes> 90 </resource> 91 <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> 92 <resource> 93 <directory>src/main/resources</directory> 94 <includes> 95 <include>*.properties</include> 96 <include>*.xml</include> 97 <include>*.yml</include> 98 </includes> 99 </resource> 100 </resources> 101 <plugins> 102 <plugin> 103 <groupId>org.mybatis.generator</groupId> 104 <artifactId>mybatis-generator-maven-plugin</artifactId> 105 <version>1.3.2</version> 106 <dependencies> 107 <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> 108 <dependency> 109 <groupId>mysql</groupId> 110 <artifactId>mysql-connector-java</artifactId> 111 <version>${mysql.version}</version> 112 </dependency> 113 </dependencies> 114 <configuration> 115 <overwrite>true</overwrite> 116 </configuration> 117 </plugin> 118 <plugin> 119 <groupId>org.springframework.boot</groupId> 120 <artifactId>spring-boot-maven-plugin</artifactId> 121 </plugin> 122 </plugins> 123 </build> 124 125 </project>
配置application.yml
springboot默认数据源是org.apache.tomcat.jdbc.pool.DataSource
1 spring: 2 datasource: 3 #1.JDBC 4 type: com.alibaba.druid.pool.DruidDataSource 5 driver-class-name: com.mysql.jdbc.Driver 6 url: jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC 7 username: root 8 password: 123 9 druid: 10 #2.连接池配置 11 #初始化连接池的连接数量 大小,最小,最大 12 initial-size: 5 13 min-idle: 5 14 max-active: 20 15 #配置获取连接等待超时的时间 16 max-wait: 60000 17 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 18 time-between-eviction-runs-millis: 60000 19 # 配置一个连接在池中最小生存的时间,单位是毫秒 20 min-evictable-idle-time-millis: 30000 21 validation-query: SELECT 1 FROM DUAL 22 test-while-idle: true 23 test-on-borrow: true 24 test-on-return: false 25 # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开 26 pool-prepared-statements: true 27 max-pool-prepared-statement-per-connection-size: 20 28 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 29 filter: 30 stat: 31 merge-sql: true 32 slow-sql-millis: 5000 33 #3.基础监控配置 34 web-stat-filter: 35 enabled: true 36 url-pattern: /* 37 #设置不统计哪些URL 38 exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" 39 session-stat-enable: true 40 session-stat-max-count: 100 41 stat-view-servlet: 42 enabled: true 43 url-pattern: /druid/* 44 reset-enable: true 45 #设置监控页面的登录名和密码 46 login-username: admin 47 login-password: admin 48 allow: 127.0.0.1 49 #deny: 192.168.1.100
启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/
测试:
HelloController
1 package com.javaqi.springboot002.controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RestController; 5 6 @RestController 7 @RequestMapping("/demo") 8 public class HelloController { 9 10 @RequestMapping("/say1") 11 public String say1(){ 12 return "说活1"; 13 } 14 15 @RequestMapping("/say2") 16 public String say2(){ 17 try { 18 Thread.sleep(2000); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 return "说活2"; 23 } 24 25 @RequestMapping("/say3") 26 public String say3(){ 27 try { 28 Thread.sleep(5000); 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 return "说活3"; 33 } 34 35 }
springboot整合mybatis
相关pom依赖
1 <resources> 2 <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> 3 <resource> 4 <directory>src/main/java</directory> 5 <includes> 6 <include>**/*.xml</include> 7 </includes> 8 </resource> 9 <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> 10 <resource> 11 <directory>src/main/resources</directory> 12 <includes> 13 <include>*.properties</include> 14 <include>*.xml</include> 15 <include>*.yml</include> 16 </includes> 17 </resource> 18 </resources> 19 20 <plugin> 21 <groupId>org.mybatis.generator</groupId> 22 <artifactId>mybatis-generator-maven-plugin</artifactId> 23 <version>1.3.2</version> 24 <dependencies> 25 <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> 26 <dependency> 27 <groupId>mysql</groupId> 28 <artifactId>mysql-connector-java</artifactId> 29 <version>${mysql.version}</version> 30 </dependency> 31 </dependencies> 32 <configuration> 33 <overwrite>true</overwrite> 34 </configuration> 35 </plugin>
逆向生成配置文件generatorConfig.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 3 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > 4 <generatorConfiguration> 5 <!-- 引入配置文件 --> 6 <properties resource="jdbc.properties"/> 7 8 <!--指定数据库jdbc驱动jar包的位置--> 9 <classPathEntry location="D:apache-maven-3.5.0-binapache-maven-3.5.0-binMvn_repositorymysqlmysql-connector-java5.1.44mysql-connector-java-5.1.44.jar"/> 10 11 <!-- 一个数据库一个context --> 12 <context id="infoGuardian"> 13 <!-- 注释 --> 14 <commentGenerator> 15 <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> 16 <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> 17 </commentGenerator> 18 19 <!-- jdbc连接 --> 20 <jdbcConnection driverClass="${jdbc.driver}" 21 connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> 22 23 <!-- 类型转换 --> 24 <javaTypeResolver> 25 <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> 26 <property name="forceBigDecimals" value="false"/> 27 </javaTypeResolver> 28 29 <!-- 01 指定javaBean生成的位置 --> 30 <!-- targetPackage:指定生成的model生成所在的包名 --> 31 <!-- targetProject:指定在该项目下所在的路径 --> 32 <javaModelGenerator targetPackage="com.javaqi.springboot002.entity" 33 targetProject="src/main/java"> 34 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 35 <property name="enableSubPackages" value="false"/> 36 <!-- 是否对model添加构造函数 --> 37 <property name="constructorBased" value="true"/> 38 <!-- 是否针对string类型的字段在set的时候进行trim调用 --> 39 <property name="trimStrings" value="false"/> 40 <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> 41 <property name="immutable" value="false"/> 42 </javaModelGenerator> 43 44 <!-- 02 指定sql映射文件生成的位置 --> 45 <sqlMapGenerator targetPackage="com.javaqi.springboot002.mapper" 46 targetProject="src/main/java"> 47 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 48 <property name="enableSubPackages" value="false"/> 49 </sqlMapGenerator> 50 51 <!-- 03 生成XxxMapper接口 --> 52 <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> 53 <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> 54 <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> 55 <javaClientGenerator targetPackage="com.javaqi.springboot002.mapper" 56 targetProject="src/main/java" type="XMLMAPPER"> 57 <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> 58 <property name="enableSubPackages" value="false"/> 59 </javaClientGenerator> 60 61 <!-- 配置表信息 --> 62 <!-- schema即为数据库名 --> 63 <!-- tableName为对应的数据库表 --> 64 <!-- domainObjectName是要生成的实体类 --> 65 <!-- enable*ByExample是否生成 example类 --> 66 67 <table schema="" tableName="t_mvc_book" domainObjectName="Book" 68 enableCountByExample="false" enableDeleteByExample="false" 69 enableSelectByExample="false" enableUpdateByExample="false"> 70 <property name="useActualColumnNames" value="true" /> 71 </table> 72 73 74 </context> 75 </generatorConfiguration>
逆向生成集成到maven中的命令
启用事物管理器
使用@Repository注解,在启动类中添加@MapperScan(“xxxx”)注解,用于扫描Mapper类的包。扫描多个包:
测试
1 package com.javaqi.springboot002.Service.impl; 2 3 4 import com.javaqi.springboot002.Service.BookService; 5 import com.javaqi.springboot002.entity.Book; 6 import com.javaqi.springboot002.util.PageBean; 7 import org.junit.jupiter.api.Test; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.boot.test.context.SpringBootTest; 10 11 /** 12 * @author XuFanQi 13 * @site 14 * @company 15 * @create 2019-11-28 16:46 16 */ 17 @SpringBootTest 18 public class BookServiceImplTest { 19 @Autowired 20 private BookService bookService; 21 22 @Test 23 public void deleteByPrimaryKey() { 24 bookService.deleteByPrimaryKey(21); 25 26 } 27 28 @Test 29 public void selectByPrimaryKey() { 30 System.out.println(bookService.selectByPrimaryKey(25)); 31 } 32 33 34 }
查询
springboot整合pagehelper
相关pom依赖
1 <dependency> 2 <groupId>com.github.pagehelper</groupId> 3 <artifactId>pagehelper-spring-boot-starter</artifactId> 4 <version>1.2.3</version> 5 </dependency>
配置application.yml文件
1 pagehelper: 2 helperDialect: mysql 3 reasonable: true 4 supportMethodsArguments: true 5 params: count=countSql 6 7 #u663Eu793Au65E5u5FD7 8 logging: 9 level: 10 com.javaxu.springboot002.mapper: debug
相关代码
BookMapper.xml
PagerAspect.java
1 package com.javaqi.springboot002.aspect; 2 3 import com.github.pagehelper.PageHelper; 4 import com.github.pagehelper.PageInfo; 5 import com.javaqi.springboot002.util.PageBean; 6 import org.aspectj.lang.ProceedingJoinPoint; 7 import org.aspectj.lang.annotation.Around; 8 import org.aspectj.lang.annotation.Aspect; 9 import org.springframework.stereotype.Component; 10 11 import java.util.List; 12 13 @Component 14 @Aspect 15 public class PagerAspect { 16 17 @Around("execution(* *..*Service.*Pager(..))") 18 public Object invoke(ProceedingJoinPoint args) throws Throwable{ 19 Object[] params = args.getArgs(); 20 PageBean pageBean = null; 21 for (Object param : params) { 22 if(param instanceof PageBean){ 23 pageBean = (PageBean) param; 24 break; 25 } 26 } 27 28 if (pageBean !=null && pageBean.isPagination()) 29 PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); 30 31 Object proceed = args.proceed(params); 32 33 if (pageBean !=null && pageBean.isPagination()){ 34 PageInfo pageInfo = new PageInfo((List)proceed); 35 pageBean.setTotal(pageInfo.getTotal()+""); 36 } 37 return proceed; 38 } 39 }
service层
测试
1 @Test 2 public void listPager() { 3 Book book = new Book(); 4 book.setBname("%圣墟%"); 5 PageBean pageBean = new PageBean(); 6 pageBean.setPage(2); 7 for (Book book1 : bookService.listPager(book, pageBean)) { 8 System.out.println(book1); 9 } 10 }