3.spring boot mybatis druid多數(shù)據(jù)源

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- ... -->
    <dependencies>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency> 
        <!-- oracle驅(qū)動 -->
        <dependency>
            <groupId>cn.easyproject</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>
        <!-- druid數(shù)據(jù)源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
        <!-- ... -->
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 如果沒有該項配置桃焕,肯呢個devtools不會起作用孩灯,即應(yīng)用不會restart -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
        <!-- 掃描src/main/java下面的xml文件. -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

2.application.yml

同一個數(shù)據(jù)源如果想配置多環(huán)境就參考

2.spring boot yml 多環(huán)境

3.在java config的形式配置數(shù)據(jù)源和mybatis

config/ds下配置數(shù)據(jù)源

MasterDataSourceConfig:

package com.yunchuang.config.ds;
import com.yunchuang.config.properties.MasterDataSourceProperties;
import com.yunchuang.utils.MyUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * @author 尹冬飛
 * @create 2017-04-07 9:57
 */
@Configuration
// 掃描 Mapper 接口并容器管理
@MapperScan(basePackages = {MasterDataSourceConfig.PACKAGE1, MasterDataSourceConfig.PACKAGE2}, sqlSessionFactoryRef = MasterDataSourceConfig.NAME + "SqlSessionFactory")
public class MasterDataSourceConfig {
    @Autowired
    private MasterDataSourceProperties masterDataSourceProperties;
    // 精確到 master 目錄厌漂,以便跟其他數(shù)據(jù)源隔離
    //dao目錄
    static final String PACKAGE1 = "com.yunchuang.dao.master";
    static final String PACKAGE2 = "com.yunchuang.dao.other";
    //xml目錄
    private static final String mapperLocation1 = "classpath:com/yunchuang/dao/master/*.xml";
    private static final String mapperLocation2 = "classpath:com/yunchuang/dao/other/*.xml";
    private static final String[] mapperLocations = {mapperLocation1, mapperLocation2};
    //全局名字前綴
    static final String NAME = "master";
    //數(shù)據(jù)源
    @Bean(name = NAME + "DataSource")
    @Primary
    public DataSource dataSource() {
        String driverClassName = masterDataSourceProperties.getDriverClassName();
        String url = masterDataSourceProperties.getUrl();
        String username = masterDataSourceProperties.getUsername();
        String password = masterDataSourceProperties.getPassword();
        return MyUtils.getDruidDataSource(driverClassName, url, username, password);
    }
    //事務(wù)管理器
    @Bean(name = NAME + "TransactionManager")
    @Primary
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
    //工廠
    @Bean(name = NAME + "SqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier(NAME + "DataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(MyUtils.resolveMapperLocations(mapperLocations));
        return sessionFactory.getObject();
    }
}

ClusterDataSourceConfig

package com.yunchuang.config.ds;
import com.yunchuang.config.properties.ClusterDataSourceProperties;
import com.yunchuang.utils.MyUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * 數(shù)據(jù)源配置
 *
 * @author 尹冬飛
 * @create 2017-04-07 9:57
 */
@Configuration
@MapperScan(basePackages = {ClusterDataSourceConfig.PACKAGE1}, sqlSessionFactoryRef = ClusterDataSourceConfig.NAME + "SqlSessionFactory")
public class ClusterDataSourceConfig {
    @Autowired
    private ClusterDataSourceProperties clusterDataSourceProperties;
    static final String PACKAGE1 = "com.yunchuang.dao.cluster";
    //xml目錄
    private static final String mapperLocation1 = "classpath:com/yunchuang/dao/cluster/*.xml";
    private static final String[] mapperLocations = {mapperLocation1};
    //全局名字前綴
    static final String NAME = "cluster";
    @Bean(name = NAME + "DataSource")
    public DataSource dataSource() {
        String driverClassName = clusterDataSourceProperties.getDriverClassName();
        String url = clusterDataSourceProperties.getUrl();
        String username = clusterDataSourceProperties.getUsername();
        String password = clusterDataSourceProperties.getPassword();
        return MyUtils.getDruidDataSource(driverClassName, url, username, password);
    }
    @Bean(name = NAME + "TransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
    @Bean(name = NAME + "SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier(NAME + "DataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(MyUtils.resolveMapperLocations(mapperLocations));
        return sessionFactory.getObject();
    }
}

utils:解決xml路徑為數(shù)組的問題

package com.yunchuang.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * 工具包
 *
 * @author 尹冬飛
 * @create 2017-04-07 16:59
 */
public class MyUtils {
    public static DruidDataSource getDruidDataSource(String driverClassName, String url, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        //這一項可配可不配垢油,如果不配置druid會根據(jù)url自動識別dbType,然后選擇相應(yīng)的driverClassName
        dataSource.setDriverClassName(driverClassName);
        //連接數(shù)據(jù)庫的url
        dataSource.setUrl(url);
        //連接數(shù)據(jù)庫的用戶名
        dataSource.setUsername(username);
        //連接數(shù)據(jù)庫的密碼
        dataSource.setPassword(password);
        //初始化時建立物理連接的個數(shù)谭网。初始化發(fā)生在顯示調(diào)用init方法歧胁,或者第一次getConnection時
        dataSource.setInitialSize(1);
        //最小連接池數(shù)量
        dataSource.setMinIdle(1);
        //最大連接池數(shù)量
        dataSource.setMaxActive(20);
        //獲取連接時最大等待時間包竹,單位毫秒。配置了maxWait之后查库,缺省啟用公平鎖路媚,并發(fā)效率會有所下降,如果需要可以通過配置useUnfairLock屬性為true使用非公平鎖樊销。
        dataSource.setMaxWait(1000);
        return dataSource;
    }
    /**
     * org.mybatis.spring.boot.autoconfigure包下MybatisProperties里面的方法直接拿來用
     *
     * @param mapperLocations xml路徑數(shù)組
     * @return 資源數(shù)組
     */
    public static Resource[] resolveMapperLocations(String[] mapperLocations) {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            String[] var3 = mapperLocations;
            int var4 = var3.length;
            for (int var5 = 0; var5 < var4; ++var5) {
                String mapperLocation = var3[var5];
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException var8) {
                    ;
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }
}

MasterDataSourceProperties和ClusterDataSourceProperties(同下)

package com.yunchuang.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * 數(shù)據(jù)源屬性文件
 *
 * @author 尹冬飛
 * @create 2017-04-07 10:57
 */
@Component
@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDataSourceProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    public String getDriverClassName() {
        return driverClassName;
    }
    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

dao接口:

package com.yunchuang.dao.master;
import com.yunchuang.domain.Person;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
 * dao接口
 *
 * @author 尹冬飛
 * @create 2017-04-07 9:38
 */
@Mapper
//@Component不加也好使,加了是為了idea能認出來
@Component
public interface IPersonDao {
    Person loadById(Integer id);
}

這樣service里就能調(diào)用了dao了.xml和dao接口放在一個包下就行.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末整慎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子围苫,更是在濱河造成了極大的恐慌裤园,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件剂府,死亡現(xiàn)場離奇詭異比然,居然都是意外死亡,警方通過查閱死者的電腦和手機周循,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進店門强法,熙熙樓的掌柜王于貴愁眉苦臉地迎上來万俗,“玉大人,你說我怎么就攤上這事饮怯「鸸剑” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵许饿,是天一觀的道長曹锨。 經(jīng)常有香客問我,道長论矾,這世上最難降的妖魔是什么教翩? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮贪壳,結(jié)果婚禮上饱亿,老公的妹妹穿的比我還像新娘。我一直安慰自己闰靴,他們只是感情好彪笼,可當(dāng)我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蚂且,像睡著了一般配猫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上杏死,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天泵肄,我揣著相機與錄音,去河邊找鬼淑翼。 笑死凡伊,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的窒舟。 我是一名探鬼主播系忙,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼惠豺!你這毒婦竟也來了银还?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤洁墙,失蹤者是張志新(化名)和其女友劉穎蛹疯,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體热监,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡捺弦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片列吼。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡幽崩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出寞钥,到底是詐尸還是另有隱情慌申,我是刑警寧澤,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布理郑,位于F島的核電站蹄溉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏您炉。R本人自食惡果不足惜柒爵,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赚爵。 院中可真熱鬧棉胀,春花似錦、人聲如沸囱晴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽畸写。三九已至,卻和暖如春氓扛,著一層夾襖步出監(jiān)牢的瞬間枯芬,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工采郎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留千所,地道東北人。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓蒜埋,卻偏偏與公主長得像淫痰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子整份,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容