欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合Mybatis使用Druid数据库连接池

程序员文章站 2022-03-10 10:52:07
本文实例为大家分享了springboot整合mybatis使用druid数据库连接池的方法,具体内容如下 在springboot项目中,增加如下依赖 <...

本文实例为大家分享了springboot整合mybatis使用druid数据库连接池的方法,具体内容如下

在springboot项目中,增加如下依赖

 <!-- 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数据库连接池 -->
    <dependency>
      <groupid>com.alibaba</groupid>
      <artifactid>druid</artifactid>
      <version>1.0.26</version>
    </dependency>

在resource目录下,创建jdbc.properties配置文件,加入以下配置

#数据库配置
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 
# 配置获取连接等待超时的时间
spring.datasource.maxwait=60000 
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timebetweenevictionrunsmillis=60000 
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minevictableidletimemillis=300000
# 测试连接是否有效的sql
spring.datasource.validationquery=select 'x'
# 建议配置为true,不影响性能,并且保证安全性
# 申请连接的时候检测,如果空闲时间大于timebetweenevictionrunsmillis,执行validationquery检测连接是否有效
spring.datasource.testwhileidle=true
# 申请连接时执行validationquery检测连接是否有效
spring.datasource.testonborrow=false
# 归还连接时执行validationquery检测连接是否有效
spring.datasource.testonreturn=false
# 要启用pscache,必须配置大于0,当大于0时,poolpreparedstatements自动触发修改为true
spring.datasource.maxpoolpreparedstatementperconnectionsize=20
# 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
# 监控统计用的filter:stat
# 日志用的filter:log4j
# 防御sql注入的filter:wall
spring.datasource.filters=stat,log4j,wall

创建数据源配置类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;

/**
 * 数据源
 *
 * @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中,首先使用被标注的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 {
    /**
     * 数据库用户名
     */
    @value("${spring.datasource.username}")
    private string username;
    /**
     * 驱动名称
     */
    @value("${spring.datasource.driver-class-name}")
    private string driverclass;
    /**
     * 数据库连接url
     */
    @value("${spring.datasource.url}")
    private string url;
    /**
     * 数据库密码
     */
    @value("${spring.datasource.password}")
    private string password;

    /**
     * 数据库连接池初始化大小
     */
    @value("${spring.datasource.initialsize}")
    private int initialsize;

    /**
     * 数据库连接池最小最小连接数
     */
    @value("${spring.datasource.minidle}")
    private int minidle;

    /**
     * 数据库连接池最大连接数
     */
    @value("${spring.datasource.maxactive}")
    private int maxactive;

    /**
     * 获取连接等待超时的时间
     */
    @value("${spring.datasource.maxwait}")
    private long maxwait;

    /**
     * 多久检测一次
     */
    @value("${spring.datasource.timebetweenevictionrunsmillis}")
    private long timebetweenevictionrunsmillis;

    /**
     * 连接在池中最小生存的时间
     */
    @value("${spring.datasource.minevictableidletimemillis}")
    private long minevictableidletimemillis;

    /**
     * 测试连接是否有效的sql
     */
    @value("${spring.datasource.validationquery}")
    private string validationquery;

    /**
     * 申请连接的时候检测,如果空闲时间大于timebetweenevictionrunsmillis,检测连接是否有效
     */
    @value("${spring.datasource.testwhileidle}")
    private boolean testwhileidle;

    /**
     * 申请连接时,检测连接是否有效
     */
    @value("${spring.datasource.testonborrow}")
    private boolean testonborrow;

    /**
     * 归还连接时,检测连接是否有效
     */
    @value("${spring.datasource.testonreturn}")
    private boolean testonreturn;

    /**
     * pscache大小
     */
    @value("${spring.datasource.maxpoolpreparedstatementperconnectionsize}")
    private int maxpoolpreparedstatementperconnectionsize;

    /**
     * 通过别名的方式配置扩展插件
     */
    @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;
    }
  }
}

创建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 // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
public class sessionfactoryconfig {

 /**
  * mybatis 配置路径
  */
 private static string mybatis_config = "mybatis-config.xml";

 @autowired
 private datasource datasource;


 /***
  * 创建sqlsessionfactorybean
  * 并且设置configtion 如驼峰命名.等等
  * 设置mapper 映射路径
  * 设置datasource数据源
  *
  * @title: createsqlsessionfactorybean
  * @author: hongyangliao
  * @date: 18-1-3 上午9:52
  * @param
  * @return org.mybatis.spring.sqlsessionfactorybean sqlsessionfactorybean实例
  * @throws
  */
 @bean(name = "sqlsessionfactory")
 public sqlsessionfactorybean createsqlsessionfactorybean() throws ioexception {
  sqlsessionfactorybean sqlsessionfactory = new sqlsessionfactorybean();
  // 设置mybatis configuration 扫描路径
  sqlsessionfactory.setconfiglocation(new classpathresource(mybatis_config));
  // 设置datasource
  sqlsessionfactory.setdatasource(datasource);
  return sqlsessionfactory;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。