spring boot +mysql + mybatis + druid的整理(一)——單數據源

一,使用spring boot腳手架搭建spring boot框架生成maven項目

以下圖所示:java

設置自定義的座標,即左側的Group和Artifact,右側能夠搜索添加一些依賴,搜索不到的能夠在pom文件中手動添加,本文須要的依賴以下:mysql

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.25</version>
        </dependency>
        <!-- 分頁插件 -->
        
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
    

引入所需依賴jar包後,就能夠開始集成mybatis和druid了。git

二,集成druid

本文采用properties文件的形式進行配置,根據本身習慣,亦可選用yml文件進行相關配置。github

1.在application.properties寫入如下配置:

#主數據庫的配置
#spring.datasource.name = test 多數據源時可配
#spring.datasource.type = com.alibaba.druid.pool.DruidDatasource
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://IP:port/數據庫名稱?useUnicode=true&amp;characterEncoding=utf8&amp;allowMultiQueries=true&amp;autoReconnect=true
spring.datasource.username = ***
spring.datasource.password = ***

#鏈接池的補充設置
#初始化、最小、最大
spring.datasource.initialSize = 1
spring.datasource.minIdle = 1
spring.datasource.maxActive = 20
#獲取鏈接等待超時的時間、毫秒(1m)
spring.datasource.maxWait = 60000
#檢測關閉空閒鏈接的間隔時間、毫秒(1m),當空閒鏈接大於(minEvictableIdleTimeMillis),則關閉物理鏈接
spring.datasource.timeBetweenEvictionRunsMillis = 60000
#一個鏈接在池中最小的生存時間、毫秒(5m)
spring.datasource.minEvictableIdleTimeMillis = 300000
#監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall用於防火牆','log4j'用於日誌
spring.datasource.druid.sys.filters = stat,wall,log4j
#用於檢測鏈接是否有效的語句
spring.datasource.validationQuery=SELECT 'x'
#檢測鏈接的超時時間、秒
spring.datasource.validationQueryTimeout = 3
#申請鏈接時,空閒時間大於(timeBetweenEvictionRunsMillis),則檢測鏈接的有效性
spring.datasource.testWhileIdle = true
#申請鏈接時,檢測鏈接的有效性(性能損耗)
spring.datasource.testOnBorrow = false
#歸還鏈接時,檢測鏈接的有效性(性能損耗)
spring.datasource.testOnReturn = false

有關druid的配置信息,可移步Druid查看,本文再也不贅述。spring

2.編寫DruidConfig,以下:

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSourceFactory;


@Configuration
public class DruidConfig {
    //配置文件
    @Autowired
    private Environment env;
    @Bean
    //默認爲主數據源
    @Primary
    public DataSource getDataSource() throws Exception{
     //此處不推薦使用實例化一個DruidDataSource的方式,進行數據源的配置,採用DruidDataSourceFactory的方式建立DataSource實例,原理分析可查看設計模式之工廠模式。 Properties properties
= new Properties(); properties.put("driverClassName", env.getProperty("spring.datasource.driverClassName")); properties.put("url", env.getProperty("spring.datasource.url")); properties.put("username", env.getProperty("spring.datasource.username")); properties.put("password", env.getProperty("spring.datasource.password")); properties.put("initialSize", env.getProperty("spring.datasource.initialSize")); properties.put("minIdle", env.getProperty("spring.datasource.minIdle")); properties.put("maxActive", env.getProperty("spring.datasource.maxActive")); properties.put("maxWait", env.getProperty("spring.datasource.maxWait")); properties.put("timeBetweenEvictionRunsMillis", env.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")); properties.put("minEvictableIdleTimeMillis", env.getProperty("spring.datasource.minEvictableIdleTimeMillis")); properties.put("validationQuery", env.getProperty("spring.datasource.validationQuery")); properties.put("filters", env.getProperty("spring.datasource.druid.sys.filters")); properties.put("validationQueryTimeout", env.getProperty("spring.datasource.validationQueryTimeout")); properties.put("testWhileIdle", env.getProperty("spring.datasource.testWhileIdle")); properties.put("testOnBorrow", env.getProperty("spring.datasource.testOnBorrow")); properties.put("testOnReturn", env.getProperty("spring.datasource.testOnReturn")); return DruidDataSourceFactory.createDataSource(properties); } }

druid集成完畢。sql

三,集成mybatis

1.在application.properties中寫入如下配置

# mybatis_config  
# mapper.xml的文件地址
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.typeAliasesPackage=****

2.編寫MybatisConfig,以下:

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.github.pagehelper.PageHelper;

@Configuration
@AutoConfigureAfter({DruidConfig.class})
//掃描dao層,basePackages 爲dao層所在路徑,支持通配符*,多個以,分隔
@MapperScan(basePackages = "")
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer{
    @Autowired
    //配置文件
    private Environment env;
    @Autowired
    //默認爲配置文件中的數據源
    DataSource dataSource;
    
    //根據數據源建立sqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //指定數據源
        factoryBean.setDataSource(dataSource);
        //指定封裝類所在包
        factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));
        //指定mapper.xml文件所在
        Resource[] resource = new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations"));
        factoryBean.setMapperLocations(resource);
        
        //添加分頁插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        factoryBean.setPlugins(new Interceptor[]{pageHelper});
        return factoryBean;
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

}

至此,集成完畢。數據庫

相關文章
相關標籤/搜索