SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池
本文實(shí)例為大家分享了SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池的方法,具體內(nèi)容如下
在SpringBoot項(xiàng)目中,增加如下依賴
<!-- spring mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid數(shù)據(jù)庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
在resource目錄下,創(chuàng)建jdbc.properties配置文件,加入以下配置
#數(shù)據(jù)庫配置 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=admin spring.datasource.password=admin spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 連接池配置 # 初始化大小,最小,最大 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置獲取連接等待超時(shí)的時(shí)間 spring.datasource.maxWait=60000 # 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 # 測(cè)試連接是否有效的sql spring.datasource.validationQuery=select 'x' # 建議配置為true,不影響性能,并且保證安全性 # 申請(qǐng)連接的時(shí)候檢測(cè),如果空閑時(shí)間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測(cè)連接是否有效 spring.datasource.testWhileIdle=true # 申請(qǐng)連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效 spring.datasource.testOnBorrow=false # 歸還連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效 spring.datasource.testOnReturn=false # 要啟用PSCache,必須配置大于0,當(dāng)大于0時(shí),poolPreparedStatements自動(dòng)觸發(fā)修改為true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 屬性類型是字符串,通過別名的方式配置擴(kuò)展插件,常用的插件有: # 監(jiān)控統(tǒng)計(jì)用的filter:stat # 日志用的filter:log4j # 防御sql注入的filter:wall spring.datasource.filters=stat,log4j,wall
創(chuàng)建數(shù)據(jù)源配置類DataSourceConfig.java,代碼如下
package com.liao.mybatis;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* 數(shù)據(jù)源
*
* @author hongyangliao
* @ClassName: DataSourceConfig
* @Date 18-1-2 下午8:56
*/
@Configuration
@MapperScan("com.liao.**.dao")
public class DataSourceConfig {
private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
@Autowired
private JdbcConfig jdbcConfig;
@Bean
@Primary //在同樣的DataSource中,首先使用被標(biāo)注的DataSource
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(jdbcConfig.getUrl());
druidDataSource.setUsername(jdbcConfig.getUserName());
druidDataSource.setPassword(jdbcConfig.getPassword());
druidDataSource.setInitialSize(jdbcConfig.getInitialSize());
druidDataSource.setMinIdle(jdbcConfig.getMinIdle());
druidDataSource.setMaxActive(jdbcConfig.getMaxActive());
druidDataSource.setTimeBetweenEvictionRunsMillis(jdbcConfig.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(jdbcConfig.getMinEvictableIdleTimeMillis());
druidDataSource.setValidationQuery(jdbcConfig.getValidationQuery());
druidDataSource.setTestWhileIdle(jdbcConfig.isTestWhileIdle());
druidDataSource.setTestOnBorrow(jdbcConfig.isTestOnBorrow());
druidDataSource.setTestOnReturn(jdbcConfig.isTestOnReturn());
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcConfig.getMaxPoolPreparedStatementPerConnectionSize());
try {
druidDataSource.setFilters(jdbcConfig.getFilters());
} catch (SQLException e) {
if (logger.isInfoEnabled()) {
logger.info(e.getMessage(), e);
}
}
return druidDataSource;
}
/**
* Jdbc配置類
*
* @author hongyangliao
* @ClassName: JdbcConfig
* @Date 18-1-2 下午9:00
*/
@PropertySource(value = "classpath:jdbc.properties")
@Component
public static class JdbcConfig {
/**
* 數(shù)據(jù)庫用戶名
*/
@Value("${spring.datasource.username}")
private String userName;
/**
* 驅(qū)動(dòng)名稱
*/
@Value("${spring.datasource.driver-class-name}")
private String driverClass;
/**
* 數(shù)據(jù)庫連接url
*/
@Value("${spring.datasource.url}")
private String url;
/**
* 數(shù)據(jù)庫密碼
*/
@Value("${spring.datasource.password}")
private String password;
/**
* 數(shù)據(jù)庫連接池初始化大小
*/
@Value("${spring.datasource.initialSize}")
private int initialSize;
/**
* 數(shù)據(jù)庫連接池最小最小連接數(shù)
*/
@Value("${spring.datasource.minIdle}")
private int minIdle;
/**
* 數(shù)據(jù)庫連接池最大連接數(shù)
*/
@Value("${spring.datasource.maxActive}")
private int maxActive;
/**
* 獲取連接等待超時(shí)的時(shí)間
*/
@Value("${spring.datasource.maxWait}")
private long maxWait;
/**
* 多久檢測(cè)一次
*/
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRunsMillis;
/**
* 連接在池中最小生存的時(shí)間
*/
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private long minEvictableIdleTimeMillis;
/**
* 測(cè)試連接是否有效的sql
*/
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
/**
* 申請(qǐng)連接的時(shí)候檢測(cè),如果空閑時(shí)間大于timeBetweenEvictionRunsMillis,檢測(cè)連接是否有效
*/
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
/**
* 申請(qǐng)連接時(shí),檢測(cè)連接是否有效
*/
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
/**
* 歸還連接時(shí),檢測(cè)連接是否有效
*/
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
/**
* PSCache大小
*/
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
/**
* 通過別名的方式配置擴(kuò)展插件
*/
@Value("${spring.datasource.filters}")
private String filters;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public long getMaxWait() {
return maxWait;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public int getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
}
創(chuàng)建Session工廠配置類SessionFactoryConfig.java,代碼如下
package com.liao.mybatis;
import java.io.IOException;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement // 啟注解事務(wù)管理,等同于xml配置方式的 <tx:annotation-driven />
public class SessionFactoryConfig {
/**
* mybatis 配置路徑
*/
private static String MYBATIS_CONFIG = "mybatis-config.xml";
@Autowired
private DataSource dataSource;
/***
* 創(chuàng)建sqlSessionFactoryBean
* 并且設(shè)置configtion 如駝峰命名.等等
* 設(shè)置mapper 映射路徑
* 設(shè)置datasource數(shù)據(jù)源
*
* @Title: createSqlSessionFactoryBean
* @author: hongyangliao
* @Date: 18-1-3 上午9:52
* @param
* @return org.mybatis.spring.SqlSessionFactoryBean sqlSessionFactoryBean實(shí)例
* @throws
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
// 設(shè)置mybatis configuration 掃描路徑
sqlSessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
// 設(shè)置datasource
sqlSessionFactory.setDataSource(dataSource);
return sqlSessionFactory;
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java synchronized同步靜態(tài)方法和同步非靜態(tài)方法的異同
這篇文章主要介紹了java synchronized同步靜態(tài)方法和同步非靜態(tài)方法的異同的相關(guān)資料,需要的朋友可以參考下2017-01-01
SpringBoot項(xiàng)目Docker部署三種方式
本文主要介紹了SpringBoot項(xiàng)目Docker部署三種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
SpringBoot項(xiàng)目配置postgresql數(shù)據(jù)庫完整步驟(配置多數(shù)據(jù)源)
PostgreSQL是一種特性非常齊全的自由軟件的對(duì)象-關(guān)系型數(shù)據(jù)庫管理系統(tǒng)(ORDBMS),下面這篇文章主要給大家介紹了關(guān)于SpringBoot項(xiàng)目配置postgresql數(shù)據(jù)庫(配置多數(shù)據(jù)源)的相關(guān)資料,需要的朋友可以參考下2023-05-05
在啟動(dòng)后臺(tái) jar包時(shí),使用指定的 application.yml操作
這篇文章主要介紹了在啟動(dòng)后臺(tái) jar包時(shí),使用指定的 application.yml操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java技巧分享之利用RxJava打造可觀測(cè)數(shù)據(jù)RxLiveData
這篇文章主要來和大家分享一個(gè)Java技巧,那就是利用RxJava打造可觀測(cè)數(shù)據(jù)RxLiveData,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-06-06
詳解Java編程中static關(guān)鍵字和final關(guān)鍵字的使用
這篇文章主要介紹了詳解Java編程中static關(guān)鍵字和final關(guān)鍵字的使用,是Java入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
SpringBoot集成Lettuce客戶端操作Redis的實(shí)現(xiàn)
本文主要介紹了SpringBoot集成Lettuce客戶端操作Redis的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
java實(shí)體類轉(zhuǎn)json時(shí)null值不要轉(zhuǎn)為"null"問題
這篇文章主要介紹了java實(shí)體類轉(zhuǎn)json時(shí)null值不要轉(zhuǎn)為“null”問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

