1. 程式人生 > >springboot 配置多資料來源

springboot 配置多資料來源

1.首先在建立應用物件時引入autoConfig

@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(Application.class);
		app.run(args);
		//SpringApplication.run(Application.class, args);
	}
	
	@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

2.其次配置檔案

######primary#############
datasource.primary.url=jdbc:sqlserver://xx.xx.xx.xx:1433;DatabaseName=PlayNowLog
datasource.primary.username=sa
datasource.primary.password=xxxxxx
datasource.primary.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver


######secondary#############
datasource.secondary.url=jdbc:sqlserver://xx.xx.xx.xx:1433;DatabaseName=PlayNow_New
datasource.secondary.username=sa
datasource.secondary.password=xxxxxx
datasource.secondary.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

3.再其次是資料來源的建立

@Configuration
public class GlobalDataConfiguration {
	@Bean(name="primaryDataSource")
	@Primary
	@ConfigurationProperties(prefix="datasource.primary")
	public DataSource primaryDataSource() {
		System.out.println("-------------------- primaryDataSource init ---------------------");
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name="secondaryDataSource")
	@ConfigurationProperties(prefix="datasource.secondary")
	public DataSource secondaryDataSource() {
		System.out.println("-------------------- secondaryDataSource init ---------------------");
		return DataSourceBuilder.create().build();
	}
}


4.Dao層使用資料來源

@Component
public class UserDaoImpl<T extends com.sonychina.backend.entity.statistic.SysUser> extends MyBatisBaseDao<SysUser> implements UserDao {
	
	@Autowired
	public UserDaoImpl(@Qualifier("secondaryDataSource") DataSource dataSource) {
		super(dataSource);
	}
}
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;

import com.sonychina.backend.global.Constants;
import com.sonychina.backend.utility.GenericsUtils;
import com.sonychina.backend.utility.MapResultHandler;
import com.sonychina.backend.utility.MyBatisUtil;
import com.sonychina.backend.utility.PageView;

public class MyBatisBaseDao<T>{
    private Class<T> type;
    private SqlSession session;
    
    @SuppressWarnings("unchecked")
	public MyBatisBaseDao(DataSource dataSource){
		type = (Class<T>) GenericsUtils.getActualReflectArgumentClass(this.getClass());
		System.out.println("------------- BaseMybatisDao initialize--------------------------");
		System.out.println("------------- T:" + type.toString());
		try {
			MyBatisUtil myBatisUtil = MyBatisUtil.getInstance(dataSource);
			session = myBatisUtil.getSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    
    private String getMethodPath(String methodType){
        return getMethodPath(methodType, "");
    }
    
    private String getMethodPath(String methodType, String methodSuffix){
        return Constants.MYBATIS_MAPPER_PRIX + methodType + type.getSimpleName() + methodSuffix;
    }
    
    public void save(T obj) {
        session.insert(getMethodPath("save"), obj);
    }

    public void delete(T obj) {
        session.delete(getMethodPath("delete"), obj);
    }

    public void update(T obj) {
        session.update(getMethodPath("update"), obj);
        //HashMap<String,Object> map = null;
    }

    public T get(Integer id) {
        return session.selectOne(getMethodPath("get"),id);
    }
    
    public List<T> getList(T entity){
    	return session.selectList(getMethodPath("get", "List"), entity);
    }
    
    public List<T> getListByAnyObject(Object entity){
    	return session.selectList(getMethodPath("get", "List"), entity);
    }
    
    /**
     * 
     * @param entity
     * @param selectId:mapper。xml檔案中<select>標籤ID
     * @return
     */
    public List<T> getList(T entity, String selectId){
    	return session.selectList(selectId, entity);
    }
    
    public List<T> getListByAnyObject(Object entity, String selectId){
    	return session.selectList(selectId, entity);
    }
    
    public List<Map<String, Object>> getMapList(Map<String, Object> map){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(getMethodPath("get", "MapList"), map, mh);
    	return mh.getMappedResults();
    }
    
    /**
     * 
     * @param map
     * @param selectId:mapper。xml檔案中<select>標籤ID
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> getMapList(Map<String, Object> map, String selectId){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(selectId, map, mh);
    	return mh.getMappedResults();
    }
    
    public List<Map<String, Object>> getMapList(T entity){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(getMethodPath("get", "MapList"), entity, mh);
    	return mh.getMappedResults();
    }

    public List<Map<String, Object>> getMapList(T entity,String queryName){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(queryName, entity, mh);
    	return mh.getMappedResults();
    }

    public Long getCount(Map<String, Object> pm){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(getMethodPath("get", "Count"),pm, mh);
    	return mh.getCount();
    }
    
    /**
     * 
     * @param pm
     * @param selectId:mapper。xml檔案中<select>標籤ID
     * @return Long
     */
    public Long getCount(Map<String,Object> pm, String selectId){
    	MapResultHandler mh = new MapResultHandler();
    	session.select(selectId,pm, mh);
    	return mh.getCount();
    }
    
    /**
     * map 中必須包含 key:currentPageNum 且其值不能為空, 頁面顯示的記錄數不是10必須包含key:pageShowCnt
     * 且其值不能為空
     * @param map
     * @return PageView
     */
    public PageView getPageList(Map<String, Object> map){
    	
    	if(map == null || map.get("currentPageNum") == null){
    		return null;
    	} else{
    		PageView page = null;
    		Integer pageNum = Integer.valueOf(map.get("currentPageNum").toString());
    		if(map.get("pageShowCnt") == null){
    			page = new PageView(pageNum);
    		} else {
    			Integer showCnt = Integer.valueOf(map.get("pageShowCnt").toString());
    			page = new PageView(pageNum, showCnt);
    		}
    		map.put("start", page.getStart());
    		map.put("end", page.getCurrentMaxCnt());
    		//System.out.println("-----------start:" + map.get("start"));
    		//System.out.println("-----------start:" + map.get("maxCnt"));
    		MapResultHandler mh = new MapResultHandler();
    		page.setTotalRecord(this.getCount(map));
        	session.select(getMethodPath("get", "MapPageList"), map, mh);
        	page.setResultList(mh.getMappedResults());
        	
        	return page;
    	}
    }
    
    /**
     * map 中必須包含 key:currentPageNum 且其值不能為空, 頁面顯示的記錄數不是10必須包含key:pageShowCnt
     * 且其值不能為空
     * @param map
     * @param selectConutId, mapper.xml檔案中<select>標籤Id, 查詢總記錄數的sql語句
     * @param selectPageListId, mapper.xml檔案中<select>標籤Id,查詢分頁後資料列表的sql語句
     * @return
     */
    public PageView getPageList(Map<String, Object> map, String selectConutId, String selectPageListId){
    	
    	if(map == null || map.get("currentPageNum") == null){
    		return null;
    	} else{
    		PageView page = null;
    		Integer pageNum = Integer.valueOf(map.get("currentPageNum").toString());
    		if(map.get("pageShowCnt") == null){
    			page = new PageView(pageNum);
    		} else {
    			Integer showCnt = Integer.valueOf(map.get("pageShowCnt").toString());
    			page = new PageView(pageNum, showCnt);
    		}
    		map.put("start", page.getStart());
    		map.put("end", page.getCurrentMaxCnt());
    		//System.out.println("-----------start:" + map.get("start"));
    		//System.out.println("-----------start:" + map.get("maxCnt"));
    		MapResultHandler mh = new MapResultHandler();
    		page.setTotalRecord(this.getCount(map, selectConutId));
        	session.select(selectPageListId, map, mh);
        	page.setResultList(mh.getMappedResults());
        	
        	return page;
    	}
    }
    
    /**
     * map 中必須包含 key:currentPageNum 且其值不能為空, 頁面顯示的記錄數不是10必須包含key:pageShowCnt
     * 且其值不能為空
     * @param map
     * @param selectConutId, mapper.xml檔案中<select>標籤Id, 查詢總記錄數的sql語句
     * @param selectPageListId, mapper.xml檔案中<select>標籤Id,查詢分頁後資料列表的sql語句
     * @return
     */
    public PageView getEntityPageList(Map<String, Object> map, String selectConutId, String selectPageListId){
    	
    	if(map == null || map.get("currentPageNum") == null){
    		return null;
    	} else{
    		PageView page = null;
    		Integer pageNum = Integer.valueOf(map.get("currentPageNum").toString());
    		if(map.get("pageShowCnt") == null){
    			page = new PageView(pageNum);
    		} else {
    			Integer showCnt = Integer.valueOf(map.get("pageShowCnt").toString());
    			page = new PageView(pageNum, showCnt);
    		}
    		map.put("start", page.getStart());
    		map.put("end", page.getCurrentMaxCnt());
    		//System.out.println("-----------start:" + map.get("start"));
    		//System.out.println("-----------start:" + map.get("maxCnt"));
    		page.setTotalRecord(this.getCount(map, selectConutId));
        	page.setResultList(session.selectList(selectPageListId, map));
        	
        	return page;
    	}
    }
    
    /**
     * map 中必須包含 key:currentPageNum 且其值不能為空, 頁面顯示的記錄數不是10必須包含key:pageShowCnt
     * 且其值不能為空
     * @param map
     * @return PageView
     */
    public PageView getEntityPageList(Map<String, Object> map){
    	
    	if(map == null || map.get("currentPageNum") == null){
    		return null;
    	} else{
    		PageView page = null;
    		Integer pageNum = Integer.valueOf(map.get("currentPageNum").toString());
    		if(map.get("pageShowCnt") == null){
    			page = new PageView(pageNum);
    		} else {
    			Integer showCnt = Integer.valueOf(map.get("pageShowCnt").toString());
    			page = new PageView(pageNum, showCnt);
    		}
    		map.put("start", page.getStart());
    		map.put("end", page.getCurrentMaxCnt());
    		//System.out.println("-----------start:" + map.get("start"));
    		//System.out.println("-----------start:" + map.get("maxCnt"));
    		page.setTotalRecord(this.getCount(map));
        	page.setResultList(session.selectList(getMethodPath("get", "PageList"), map));
        	
        	return page;
    	}
    }
}

相關推薦

springboot配置資料來源之Spring Date JPA

多資料來源在專案開發中是經常遇到的,如果同一個專案的不同模組使用的是不同資料庫,就需要多資料來源的處理。現在先寫之前使用JPA的時候遇到多資料來源的配置,後續可能再來個關於mybatis的多資料來源配置。 現在有這樣的需求,專案中有兩個模組,分別是flow與imap,flow需要使用預設資料

springboot配置資料來源(MongoDB主從)

相信看過上一篇文章的小夥伴已經知道了, 這章要講的就是MongoDB主從配置。 在這邊文章中,你將要學到的是在專案中配置主從資料庫,並且相容其他資料庫喲。。這些都是博主專案中需要並且比較重要的知識哦~ 好了,廢話不多說,直接進主題。 1.pom依賴 <depende

springboot配置資料來源(不同DB)

springBoot整合Mysql+MongoDB 因為在專案中需要用到兩個不同的資料來源。但是又不存在於一個DB中。讓我很是苦惱,不得已只能整合多資料來源。 博主文筆不好,只能講乾貨了。。 目標: 使用springBoot整合mys

手把手教你用springboot配置資料來源

<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache

SpringBoot配置資料來源(druid)

分析 spring本身是支援多資料來源動態切換的,AbstractRoutingDataSource這個抽象類就是spring提供的一個數據源路由的一個入口,該抽象類暴露了一個determineCurrentLookupKey()的方法,該方法返回值是Object,該返回值作為key

SpringBoot配置資料來源(MySQL+SQLServer)

SpringBoot 版本 1.5.13.RELEASE,以下maven依賴中包含jpa、web、mysql驅動、sqlserver驅動、測試模組。(按需新增) <parent> <groupId>org.springframework.

springboot配置資料來源並整合Druid

1.application.properties配置檔案 spring.datasource.type = com.alibaba.druid.pool.DruidDataSource #----DS1---- spring.datasource.primary.u

springboot配置資料來源,註解操作資料庫

最近新搭建了一個專案,需要去不同的資料庫中查詢資料,需要多個數據源,在網上搜索了下,基本上實現都很複雜,下面我自己實現了一個很簡單的配置方法。 1、原來我們都是在application.yml檔案中配置資料來源,現在不需要在application.yml檔案中配置了。   &n

springboot 配置資料來源

1.首先在建立應用物件時引入autoConfig @ComponentScan @EnableAutoConfiguration public class Application extends SpringBootServletInitializer { public

springboot配置資料來源 mybatis

application.yml配置 spring.datasource.primary.url=jdbc:mysql://192.168.10.109:3306/demo spring.datasource.primary.username=root spring.dat

springboot配置資料來源java.lang.IllegalArgumentException: At least one JPA metamodel must be present!

前言      springboot 專案啟動時遇到問題: At least one JPA metamodel must be present! ,怎麼解決的呢,下面來一起看下。 正文 問題再現

SpringBoot配置資料來源

SpringBoot下配置多資料來源,有的時候我們的專案可能需要從不同的資料來源獲取或者操作資料,這個時候就需要配置多資料來源; 環境 Spring-Boot 1.5.3.RELEASE 、JDK1.8、HikariDataSource 搭建SpringBoot

SpringBoot配置資料來源(結合Druid)

在單資料來源的情況下,Spring Boot的配置非常簡單,只需要在application.properties檔案中配置連線引數即可。但是往往隨著業務量發展,我們通常會進行資料庫拆分或是引入其他資料庫,從而我們需要配置多個數據源,下面介紹多資料來源的配置方式。

springboot整合Mybatis配置資料來源

springboot配置多資料來源有好幾種方式 1.application.properties配置 ## 埠 server.port=8080 # 資料庫訪問配置 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spri

springboot使用mybatis如何配置資料來源

本篇部落格提供一個工程想連線多個數據庫進行業務查詢,在原先的單個數據庫上進行配置實現多個數據庫的使用,對於springboot以及mybatis不在此進行展開介紹,只需要把程式碼按照步驟一步步貼上進你的專案,調整一下就能實現; 簡單介紹單個數據源配置 pom檔案匯入依賴 <

實現SpringBoot資料來源配置

【場景】 當業務資料量達到了一定程度,DBA 需要合理配置資料庫資源。即配置主庫的機器高配置,把核心高頻的資料放在主庫上;把次要的資料放在從庫,低配置。 –(引自 https://www.cnblogs.com/Alandre/p/6611813.html 泥瓦匠BYSocket

springboot+mybatis資料來源配置,AOP註解動態切換資料來源

轉載至:https://blog.csdn.net/xiaosheng_papa/article/details/80218006 親測有效。 注:有些系統中已經配置了單資料來源,現在要轉成多資料來源,可能需要額外的配置。拿我自己當前專案來說: 專案在啟動類中配置了單資料來源:

基於SpirngBoot2.0+ 的 SpringBoot+Mybatis 資料來源配置

Github 地址:github.com/Snailclimb/…(SpringBoot和其他常用技術的整合,可能是你遇到的講解最詳細的學習案例,力爭新手也能看懂並且能夠在看完之後獨立實踐。基於最新的 SpringBoot2.0+,是你學習SpringBoot 的最佳指南。) ,歡迎各位 Star。

新手也能看懂,基於SpirngBoot2.0+ 的 SpringBoot+Mybatis 資料來源配置

Github 地址:https://github.com/Snailclimb/springboot-integration-examples(SpringBoot和其他常用技術的整合,可能是你遇到的講解最詳細的學習案例,力爭新手也能看懂並且能夠在看完之後獨立實踐。基於最新的 S

springboot+mybatis資料來源配置實現

簡單實現了根據註解動態切換資料來源,支援同一個資料庫的宣告式事務,但不支援JTA事務。處理流程: 根據配置的資料來源資訊,建立動態資料來源bean 利用DataSourceAspect處理@DataSource註解,設定當前要使用的具體資料來源 pom.xm