springboot之Druid連線池講解+mybatis整合+PageHelper整合
轉載請標明出處:https://blog.csdn.net/men_ma/article/details/106847165.
本文出自 不怕報錯 就怕不報錯的小猿猿 的部落格
springboot之Druid連線池講解+mybatis整合+PageHelper整合
目標
1、springboot配置資料庫連線池druid
2、springboot整合mybatis
3、springboot整合pagehelper
前期準備工作環境(新建springboot環境)
專案目錄結構
1.springboot配置資料庫連線池druid
1.1 druid學習地址
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
1.2 相關pom依賴
druid所需pom依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
特別注意:一定要修改springboot的版本號,博主在這裡踩了一個大坑,坑死我了,之前springboot版本用的2.4.0的,導致後面有些功能出不來,springboot之間的版本真的是有很大的差異,親測過,坑死我了,我喊冤啊!!!!
注意2:我們還要降低mysql的版本號,原本是8.0.幾的版本的,現在我們降到5.1.44
<mysql.version>5.1.44</mysql.version>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
1.3 配置application.yml
server:
port: 8080
servlet:
context-path: /
spring:
datasource:
#1.JDBC
#com.alibaba.druid.pool.DruidDataSource:Druid資料來源
type: com.alibaba.druid.pool.DruidDataSource
# 驅動包
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/t243?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123
druid:
#2.連線池配置
#初始化連線池的連線數量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置獲取連線等待超時的時間
max-wait: 60000
#配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一個連線在池中最小生存的時間,單位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否快取preparedStatement,也就是PSCache 官方建議MySQL下建議關閉 個人建議如果想用SQL防火牆 建議開啟
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基礎監控配置
web-stat-filter:
enabled: true
url-pattern: /*
#設定不統計哪些URL 監控平臺:除了以下的不監控其他的都要監控
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
#druid監控平臺的請求地址
url-pattern: /druid/*
reset-enable: true
#設定監控頁面的登入名和密碼
login-username: admin
login-password: admin
#這個專案的監控平臺只能被本機的訪問
allow: 127.0.0.1
#deny: 192.168.1.100
配置檔案中需要注意的地方:
1.4 測試監控平臺的後臺程式碼HelloController
package com.xiaoqing.springboot02.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author晴sister
* @site https://blog.csdn.net/men_ma
* @company xxx公司
* @create 2020-11-30 1:42
*/
@RestController
@RequestMapping("/demo")
public class HelloController {
@RequestMapping("/say1")
public String say1(){
return "說活1";
}
@RequestMapping("/say2")
public String say2(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "說活2";
}
@RequestMapping("/say3")
public String say3(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "說活3";
}
}
1.5 springboot整合druid成功截圖
啟動SpringBoot專案訪問druid, http://localhost:tomcat埠號/專案名稱/druid/
springboot之Druid連線池就整合成功啦
2.springboot整合mybatis
2.1 springboot整合mybatis逆向生成外掛
匯入相關pom依賴:
<!--更改springboot中的mysql版本,逆向生成不相容高版本-->
<mysql.version>5.1.44</mysql.version>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<resources>
<!--解決mybatis-generator-maven-plugin執行時沒有將XxxMapper.xml檔案放入target資料夾的問題-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--解決mybatis-generator-maven-plugin執行時沒有將jdbc.properites檔案放入target資料夾的問題-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
<include>*.xml</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator外掛不能使用太高版本的mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
2.2 逆向生成配置檔案generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置檔案 -->
<properties resource="jdbc.properties"/>
<!--指定資料庫jdbc驅動jar包的位置-->
<classPathEntry location="D:\initPath\mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
<!-- 一個資料庫一個context -->
<context id="infoGuardian">
<!-- 註釋 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消註釋 -->
<property name="suppressDate" value="true"/> <!-- 是否生成註釋代時間戳 -->
</commentGenerator>
<!-- jdbc連線 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 型別轉換 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自動轉化以下型別(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在該專案下所在的路徑 -->
<javaModelGenerator targetPackage="com.xiaoqing.springboot02.entity"
targetProject="src/main/java">
<!-- 是否允許子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否對model新增建構函式 -->
<property name="constructorBased" value="true"/>
<!-- 是否針對string型別的欄位在set的時候進行trim呼叫 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model物件是否 不可改變 即生成的Model物件不會有 setter方法,只有構造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql對映檔案生成的位置 -->
<sqlMapGenerator targetPackage="com.xiaoqing.springboot02.mapper"
targetProject="src/main/java">
<!-- 是否允許子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper介面 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper物件 -->
<!-- type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper物件 -->
<!-- type="XMLMAPPER",生成SQLMap XML檔案和獨立的Mapper介面 -->
<javaClientGenerator targetPackage="com.xiaoqing.springboot02.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在當前路徑下新加一層schema,false路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表資訊 -->
<!-- schema即為資料庫名 -->
<!-- tableName為對應的資料庫表 -->
<!-- domainObjectName是要生成的實體類 -->
<!-- enable*ByExample是否生成 example類 -->
<table schema="" tableName="t_mvc_book" domainObjectName="Book"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<property name="useActualColumnNames" value="true" />
</table>
</context>
</generatorConfiguration>
2.3 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/t243?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
2.4 springboot整合mybatis
使用@Repository註解,在啟動類中新增@MapperScan(“xxxx”)註解,用於掃描Mapper類的包。掃描多個包:@MapperScan({com.javaxl.springboot02.dao”,”com.javaxl.springboot02.entity”}) //啟用事物管理器
@EnableTransactionManagement
package com.xiaoqing.springboot02;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @EnableTransactionManagement:開啟事務管理
* @EnableAspectJAutoProxy:開啟動態代理
* @MapperScan:掃描基包
*/
@MapperScan("com.xiaoqing.springboot02.mapper")
@EnableTransactionManagement
@EnableAspectJAutoProxy
@SpringBootApplication
public class Springboot02Application {
public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}
}
2.5 測試程式碼
package com.xiaoqing.springboot02;
import com.xiaoqing.springboot02.entity.Book;
import com.xiaoqing.springboot02.service.BookService;
import com.xiaoqing.springboot02.utils.PageBean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Springboot02Application.class)
public class Springboot02ApplicationTests {
@Autowired
private BookService bookService;
@Test
public void select() {
System.out.println(this.bookService.selectByPrimaryKey(22));
}
@Test
public void delete() {
this.bookService.deleteByPrimaryKey(20);
}
}
}
2.6 測試結果
3.springboot整合pagehelper
3.1 匯入相關pom依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
3.2 配置application.yml檔案
#pagehelper分頁外掛配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
#顯示日誌
logging:
level:
com.javaxl.springboot02.mapper: debug
3.3 相關程式碼:
mapper.java:
List<Book> queryBooksPager(Book book);
mapper.xml:
<select id="queryBooksPager" resultType="com.xiaoqing.springboot02.entity.Book" parameterType="com.xiaoqing.springboot02.entity.Book">
select
<include refid="Base_Column_List" />
from t_mvc_book
<where>
<if test="bname != null and bname !=''">
bname like #{bname}
</if>
</where>
</select>
PageAspect.java:
package com.xiaoqing.springboot02.aop;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoqing.springboot02.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author 晴sister
* @site https://blog.csdn.net/men_ma
* @company
* @create 2020-10-1123:14
*/
@Component
@Aspect
public class PageAspect {
@Around("execution(* *..*Service.*Pager(..))")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable{
// 獲取目標物件方法的引數集合
// BookService.listPager(map,pagebean)
Object[] args = joinPoint.getArgs();
PageBean pageBean=null;
// 利用環繞通知
// args:目標物件引數=map+pagebean
for (Object arg : args) {
// 如果arg中包含pagebean,則進入if
if(arg instanceof PageBean){
// 強轉為pagebean,向下轉型
pageBean=(PageBean) arg;
break;
}
}
if(pageBean!=null&&pageBean.isPagination()){
// 開始分頁
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
// 目標執行
Object proceed = joinPoint.proceed(args);
if(pageBean!=null&&pageBean.isPagination()){
PageInfo pageInfo=new PageInfo((List) proceed);
pageBean.setTotal(pageInfo.getTotal()+"");
}
return proceed;
}
}
springboot啟動類Springboot02Application:
package com.xiaoqing.springboot02;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @EnableTransactionManagement:開啟事務管理
* @EnableAspectJAutoProxy:開啟動態代理
* @MapperScan:掃描基包
*/
@MapperScan("com.xiaoqing.springboot02.mapper")
@EnableTransactionManagement
@EnableAspectJAutoProxy
@SpringBootApplication
public class Springboot02Application {
public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}
}
service層:
public List<Book> queryBooksPager(Book book, PageBean pageBean) {
return bookMapper.queryBooksPager(book);
}
3.4 測試程式碼
Springboot02ApplicationTests:
package com.xiaoqing.springboot02;
import com.xiaoqing.springboot02.entity.Book;
import com.xiaoqing.springboot02.service.BookService;
import com.xiaoqing.springboot02.utils.PageBean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Springboot02Application.class)
public class Springboot02ApplicationTests {
@Autowired
private BookService bookService;
@Test
public void queryBookPager() {
Book book=new Book();
book.setBname("%聖%");
PageBean pageBean=new PageBean();
for(Book b: this.bookService.queryBooksPager(book,null)){
System.out.println(b);
}
}
}
3.5 控制檯截圖及測試結果
小結
SpringBoot啟動項配置,,通常容易被忘記:
//自動掃描Mapper目錄
@MapperScan(“com.javaxl.專案名.mapper”)
//啟用事物管理器
@EnableTransactionManagement
//啟用動態代理
@EnableAspectJAutoProxy
相關文章
- SpringBoot專案整合阿里Druid連線池Spring Boot阿里UI
- Springboot 整合阿里資料庫連線池 druidSpring Boot阿里資料庫UI
- springboot專案整合druid資料庫連線池Spring BootUI資料庫
- MyBatis學習-使用Druid連線池將Maybatis整合到springMyBatisUISpring
- SpringBoot整合Mybatis+DruidSpring BootMyBatisUI
- Spring系列之整合Druid連線池及監控配置SpringUI
- 【springboot】學習4:整合JDBC、整合druid、整合mybatis、整合 SpringSecuritySpring BootJDBCUIMyBatisGse
- SpringBoot 整合Mybatis + PageHelper 實現分頁Spring BootMyBatis
- Spring Boot整合Druid資料庫連線池Spring BootUI資料庫
- Springboot整合pagehelperSpring Boot
- SpringBoot2 基礎案例(07):整合Druid連線池,配置監控介面Spring BootUI
- SpringBoot 整合多資料來源(MyBatis + Druid)Spring BootMyBatisUI
- springboot整合druidSpring BootUI
- SpringBoot整合mybatis-plus,pagehelper以及程式碼自動生成Spring BootMyBatis
- SpringBoot整合MyBatis的分頁外掛PageHelper(回頭草)Spring BootMyBatis
- MyBatis初級實戰之三:springboot整合druidMyBatisSpring BootUI
- 連線池 druidUI
- springboot activiti 整合專案框架原始碼 shiro 安全框架 druid 資料庫連線池Spring Boot框架原始碼UI資料庫
- SpringBoot學習之整合MybatisSpring BootMyBatis
- springBoot 整合 mybatisSpring BootMyBatis
- Springboot整合MybatisSpring BootMyBatis
- SpringBoot中使用Mybatis-plus整合PageHelper分頁外掛踩坑Spring BootMyBatis
- SpringBoot整合系列–整合MyBatis-plusSpring BootMyBatis
- SpringBoot資料訪問之整合mybatis註解版Spring BootMyBatis
- springboot+mybatis整合Spring BootMyBatis
- SpringBoot | 3.2 整合MyBatisSpring BootMyBatis
- Springboot+mybatis 整合Spring BootMyBatis
- SpringBoot?整合mongoDB並自定義連線池的示例程式碼Spring BootMongoDB
- SpringBoot整合Druid資料來源Spring BootUI
- springBoot 整合 mybatis+OracleSpring BootMyBatisOracle
- SpringBoot整合Mybatis-PlusSpring BootMyBatis
- springboot專案整合mybatisSpring BootMyBatis
- springboot-整合mybatis,securitySpring BootMyBatis
- Druid資料來源使用(一)---單獨使用與整合springboot+mybatisUISpring BootMyBatis
- SpringBoot使用Mybatis-PageHelperSpring BootMyBatis
- druid連線池常見異常UI
- 聊聊資料庫連線池 Druid資料庫UI
- Druid-目前最好的連線池UI