SpringBoot+Druid+Mybatis閰嶇疆澶氭暟鎹簮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot+Druid+Mybatis閰嶇疆澶氭暟鎹簮相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/ntp' title='ntp'>ntp   ssl   濂界殑   杩橀渶   return   鍒嗕韩鍥剧墖   cat   鎯呭喌   throw   

鎴戜滑鍦ㄥ紑鍙戜竴涓」鐩殑鏃跺€欙紝鍙兘浼氶亣鍒伴渶瑕佸澶氫釜鏁版嵁搴撹繘琛岃鍐欑殑闇€姹傦紝杩欐椂鍊欏氨寰楀湪椤圭洰涓厤缃涓暟鎹簮浜嗐€傚湪Java椤圭洰鐨勫紑鍙戜腑锛岀洰鍓嶆渶甯哥敤鐨勬暟鎹搷浣滄鏋舵槸 Mybatis锛屽紑鍙戞鏋朵篃閮藉熀鏈敤涓婁簡SpringBoot銆傝€孌ruid鍙风О鏈€濂界殑鏁版嵁搴撹繛鎺ユ睜锛岃嚜鐒朵篃鏄骞挎硾浣跨敤銆?/p>

鎵€浠ユ湰鏂囧皢婕旂ず涓€涓嬶紝SpringBoot+Druid+Mybatis濡備綍鍘婚厤缃鏁版嵁婧愩€傞鍏堝湪IDEA涓垱寤轰竴涓猄pringBoot宸ョ▼锛?br/>鎶€鏈垎浜浘鐗? src=
鎶€鏈垎浜浘鐗? src=

閫夋嫨涓€浜涘熀鏈殑鍖咃細
鎶€鏈垎浜浘鐗? src=

瀹屾垚鍒涘缓锛?br/>鎶€鏈垎浜浘鐗? src=

pom.xml閰嶇疆鐨勪緷璧栧涓嬶細

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- alibaba鐨刣ruid鏁版嵁搴撹繛鎺ユ睜 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.9</version>
    </dependency>
</dependencies>

鎺ョ潃灏辨槸缂栬緫SpringBoot鐨勯厤缃枃浠讹紝鎴戣繖閲屼娇鐢ㄧ殑鏄痽ml鏍煎紡鐨勩€傞渶瑕佹敞鎰忕殑鏄紝鍦ㄤ娇鐢ㄥ鏁版嵁婧愮殑鎯呭喌涓嬶紝蹇呴』鍖哄垎鍑轰富鏁版嵁婧愬拰浠庢暟鎹簮锛屽惁鍒欎細鎶ラ敊銆俛pplication.yml閰嶇疆鏂囦欢鍐呭濡備笅锛?/p>

spring:
  datasource:
    #浣跨敤druid杩炴帴姹?    type: com.alibaba.druid.pool.DruidDataSource

# 鑷畾涔夌殑涓绘暟鎹簮閰嶇疆淇℃伅
primary:
  datasource:
    #druid鐩稿叧閰嶇疆
    druid:
      #鐩戞帶缁熻鎷︽埅鐨刦ilters
      filters: stat
      driverClassName: com.mysql.jdbc.Driver
      #閰嶇疆鍩烘湰灞炴€?      url: jdbc:mysql://127.0.0.1:3306/primary_database?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false
      username: root
      password: password
      #閰嶇疆鍒濆鍖栧ぇ灏?鏈€灏?鏈€澶?      initialSize: 1
      minIdle: 1
      maxActive: 20
      #鑾峰彇杩炴帴绛夊緟瓒呮椂鏃堕棿
      maxWait: 60000
      #闂撮殧澶氫箙杩涜涓€娆℃娴嬶紝妫€娴嬮渶瑕佸叧闂殑绌洪棽杩炴帴
      timeBetweenEvictionRunsMillis: 60000
      #涓€涓繛鎺ュ湪姹犱腑鏈€灏忕敓瀛樼殑鏃堕棿
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 鈥榵鈥?      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #鎵撳紑PSCache锛屽苟鎸囧畾姣忎釜杩炴帴涓奝SCache鐨勫ぇ灏忋€俹racle璁句负true锛宮ysql璁句负false銆傚垎搴撳垎琛ㄨ緝澶氭帹鑽愯缃负false
      poolPreparedStatements: false
      maxPoolPreparedStatementPerConnectionSize: 20

# 鑷畾涔夌殑浠庢暟鎹簮閰嶇疆淇℃伅
back:
  datasource:
    #druid鐩稿叧閰嶇疆
    druid:
      #鐩戞帶缁熻鎷︽埅鐨刦ilters
      filters: stat
      driverClassName: com.mysql.jdbc.Driver
      #閰嶇疆鍩烘湰灞炴€?      url: jdbc:mysql://127.0.0.1:3306/back_database?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false
      username: root
      password: password
      #閰嶇疆鍒濆鍖栧ぇ灏?鏈€灏?鏈€澶?      initialSize: 1
      minIdle: 1
      maxActive: 20
      #鑾峰彇杩炴帴绛夊緟瓒呮椂鏃堕棿
      maxWait: 60000
      #闂撮殧澶氫箙杩涜涓€娆℃娴嬶紝妫€娴嬮渶瑕佸叧闂殑绌洪棽杩炴帴
      timeBetweenEvictionRunsMillis: 60000
      #涓€涓繛鎺ュ湪姹犱腑鏈€灏忕敓瀛樼殑鏃堕棿
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 鈥榵鈥?      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #鎵撳紑PSCache锛屽苟鎸囧畾姣忎釜杩炴帴涓奝SCache鐨勫ぇ灏忋€俹racle璁句负true锛宮ysql璁句负false銆傚垎搴撳垎琛ㄨ緝澶氭帹鑽愯缃负false
      poolPreparedStatements: false
      maxPoolPreparedStatementPerConnectionSize: 20

鐒跺悗鍦ㄩ」鐩腑鏂板缓涓€涓猚onfig鍖咃紝骞跺湪璇ュ寘涓嬪垱寤轰竴涓狿rimaryDataBaseConfig绫伙紝浣滀负鎴戜滑鐨勪富鏁版嵁婧愰厤缃被锛岀敤浜庡姞杞借嚜瀹氫箟鐨勪富鏁版嵁婧愰厤缃俊鎭紝浠ュ強鍒涘缓鏁版嵁婧愬拰浼氳瘽杩炴帴宸ュ巶绛夊疄渚嬶細

package com.dabo.mini.game.zhaxinle.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @ProjectName zhaxinle
 * @Author: zeroJun
 * @Date: 2018/8/16 16:49
 * @Description: 涓绘暟鎹簮閰嶇疆绫? */
@Data
@Configuration
// 鍓嶇紑涓簆rimary.datasource.druid鐨勯厤缃俊鎭?@ConfigurationProperties(prefix = "primary.datasource.druid")
@MapperScan(basePackages = PrimaryDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataBaseConfig {

    /**
     * dao灞傜殑鍖呰矾寰?     */
    static final String PACKAGE = "com.dabo.mini.game.zhaxinle.dao.primary";

    /**
     * mapper鏂囦欢鐨勭浉瀵硅矾寰?     */
    private static final String MAPPER_LOCATION = "classpath:mappers/primary/*.xml";

    private String filters;
    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private int initialSize;
    private int minIdle;
    private int maxActive;
    private long maxWait;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;

    // 涓绘暟鎹簮浣跨敤@Primary娉ㄨВ杩涜鏍囪瘑
    @Primary
    @Bean(name = "primaryDataSource")
    public DataSource primaryDataSource() throws SQLException {
        DruidDataSource druid = new DruidDataSource();
        // 鐩戞帶缁熻鎷︽埅鐨刦ilters
        druid.setFilters(filters);

        // 閰嶇疆鍩烘湰灞炴€?        druid.setDriverClassName(driverClassName);
        druid.setUsername(username);
        druid.setPassword(password);
        druid.setUrl(url);

        //鍒濆鍖栨椂寤虹珛鐗╃悊杩炴帴鐨勪釜鏁?        druid.setInitialSize(initialSize);
        //鏈€澶ц繛鎺ユ睜鏁伴噺
        druid.setMaxActive(maxActive);
        //鏈€灏忚繛鎺ユ睜鏁伴噺
        druid.setMinIdle(minIdle);
        //鑾峰彇杩炴帴鏃舵渶澶х瓑寰呮椂闂达紝鍗曚綅姣銆?        druid.setMaxWait(maxWait);
        //闂撮殧澶氫箙杩涜涓€娆℃娴嬶紝妫€娴嬮渶瑕佸叧闂殑绌洪棽杩炴帴
        druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        //涓€涓繛鎺ュ湪姹犱腑鏈€灏忕敓瀛樼殑鏃堕棿
        druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        //鐢ㄦ潵妫€娴嬭繛鎺ユ槸鍚︽湁鏁堢殑sql
        druid.setValidationQuery(validationQuery);
        //寤鸿閰嶇疆涓簍rue锛屼笉褰卞搷鎬ц兘锛屽苟涓斾繚璇佸畨鍏ㄦ€с€?        druid.setTestWhileIdle(testWhileIdle);
        //鐢宠杩炴帴鏃舵墽琛寁alidationQuery妫€娴嬭繛鎺ユ槸鍚︽湁鏁?        druid.setTestOnBorrow(testOnBorrow);
        druid.setTestOnReturn(testOnReturn);
        //鏄惁缂撳瓨preparedStatement锛屼篃灏辨槸PSCache锛宱racle璁句负true锛宮ysql璁句负false銆傚垎搴撳垎琛ㄨ緝澶氭帹鑽愯缃负false
        druid.setPoolPreparedStatements(poolPreparedStatements);
        // 鎵撳紑PSCache鏃讹紝鎸囧畾姣忎釜杩炴帴涓奝SCache鐨勫ぇ灏?        druid.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        return druid;
    }

    // 鍒涘缓璇ユ暟鎹簮鐨勪簨鍔$鐞?    @Primary
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(primaryDataSource());
    }

    // 鍒涘缓Mybatis鐨勮繛鎺ヤ細璇濆伐鍘傚疄渚?    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(primaryDataSource);  // 璁剧疆鏁版嵁婧恇ean
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(PrimaryDataBaseConfig.MAPPER_LOCATION));  // 璁剧疆mapper鏂囦欢璺緞

        return sessionFactory.getObject();
    }
}

鍚屾牱鐨勶紝杩橀渶瑕佸垱寤轰竴涓粠鏁版嵁婧愰厤缃被锛屼笌涓绘暟鎹簮閰嶇疆绫讳笉鍚岀殑鏄紝浠庢暟鎹簮閰嶇疆绫讳笉鑳戒娇鐢?code>@Primary娉ㄨВ锛屽嵆琛ㄧず瀹冩槸涓€涓粠鏁版嵁婧愩€備唬鐮佸涓嬶細

package com.dabo.mini.game.zhaxinle.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @ProjectName zhaxinle
 * @Author: zeroJun
 * @Date: 2018/8/16 16:49
 * @Description: 鍚庡彴鏁版嵁婧愰厤缃被
 */

@Data
@Configuration
@ConfigurationProperties(prefix = "back.datasource.druid")
@MapperScan(basePackages = BackDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "backSqlSessionFactory")
public class BackDataBaseConfig {

    /**
     * dao灞傜殑鍖呰矾寰?     */
    static final String PACKAGE = "com.dabo.mini.game.zhaxinle.dao.back";

    /**
     * mapper鏂囦欢鐨勭浉瀵硅矾寰?     */
    private static final String MAPPER_LOCATION = "classpath:mappers/back/*.xml";

    private String filters;
    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private int initialSize;
    private int minIdle;
    private int maxActive;
    private long maxWait;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;

    @Bean(name = "backDataSource")
    public DataSource backDataSource() throws SQLException {
        DruidDataSource druid = new DruidDataSource();
        // 鐩戞帶缁熻鎷︽埅鐨刦ilters
        druid.setFilters(filters);

        // 閰嶇疆鍩烘湰灞炴€?        druid.setDriverClassName(driverClassName);
        druid.setUsername(username);
        druid.setPassword(password);
        druid.setUrl(url);

        //鍒濆鍖栨椂寤虹珛鐗╃悊杩炴帴鐨勪釜鏁?        druid.setInitialSize(initialSize);
        //鏈€澶ц繛鎺ユ睜鏁伴噺
        druid.setMaxActive(maxActive);
        //鏈€灏忚繛鎺ユ睜鏁伴噺
        druid.setMinIdle(minIdle);
        //鑾峰彇杩炴帴鏃舵渶澶х瓑寰呮椂闂达紝鍗曚綅姣銆?        druid.setMaxWait(maxWait);
        //闂撮殧澶氫箙杩涜涓€娆℃娴嬶紝妫€娴嬮渶瑕佸叧闂殑绌洪棽杩炴帴
        druid.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        //涓€涓繛鎺ュ湪姹犱腑鏈€灏忕敓瀛樼殑鏃堕棿
        druid.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        //鐢ㄦ潵妫€娴嬭繛鎺ユ槸鍚︽湁鏁堢殑sql
        druid.setValidationQuery(validationQuery);
        //寤鸿閰嶇疆涓簍rue锛屼笉褰卞搷鎬ц兘锛屽苟涓斾繚璇佸畨鍏ㄦ€с€?        druid.setTestWhileIdle(testWhileIdle);
        //鐢宠杩炴帴鏃舵墽琛寁alidationQuery妫€娴嬭繛鎺ユ槸鍚︽湁鏁?        druid.setTestOnBorrow(testOnBorrow);
        druid.setTestOnReturn(testOnReturn);
        //鏄惁缂撳瓨preparedStatement锛屼篃灏辨槸PSCache锛宱racle璁句负true锛宮ysql璁句负false銆傚垎搴撳垎琛ㄨ緝澶氭帹鑽愯缃负false
        druid.setPoolPreparedStatements(poolPreparedStatements);
        // 鎵撳紑PSCache鏃讹紝鎸囧畾姣忎釜杩炴帴涓奝SCache鐨勫ぇ灏?        druid.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        return druid;
    }

    @Bean(name = "backTransactionManager")
    public DataSourceTransactionManager backTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(backDataSource());
    }

    @Bean(name = "backSqlSessionFactory")
    public SqlSessionFactory backSqlSessionFactory(@Qualifier("backDataSource") DataSource backDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(backDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(BackDataBaseConfig.MAPPER_LOCATION));

        return sessionFactory.getObject();
    }
}

瀹屾垚浠ヤ笂閰嶇疆鍚庯紝璇ュ伐绋嬪氨鍏锋湁杩炴帴涓や釜鏁版嵁搴撶殑鑳藉姏浜嗭紝濡傛灉瑕侀厤缃袱涓互涓婄殑鏁版嵁搴撲篃鏄竴鏍风殑锛岄厤缃涓粠鏁版嵁婧愬嵆鍙€備笟鍔′唬鐮佸眰闈㈤櫎浜嗛渶瑕佸皢涓嶅悓鐨勬暟鎹簮鐩稿叧鐨刴apper銆乨ao銆乸ojo鍒嗗寘瀛樻斁鏂逛究鎵弿涔嬪锛屼唬鐮佷笂鐨勭紪鍐欒繕鏄拰涔嬪墠鍗曟暟鎹簮鐨勬椂鍊欎竴鏍凤紝鎵€浠ヨ繖閲屽氨涓嶈创鍑轰笟鍔′唬鐮佷簡銆?/p>

以上是关于SpringBoot+Druid+Mybatis閰嶇疆澶氭暟鎹簮的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot系列七:SpringBoot 集成 MyBatis事物配置及使用druid 数据源druid 监控使用

SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页

SpringBoot + mybatis + druid 配置两个数据源

SpringBoot--整合Mybatis+druid

springboot + mybatis +druid

SpringBoot MyBatis druid数据库连接池