首页 > 编程

springboot 配置多数据源

2015-11-28 21:08:43 分类: 编程

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;
    	}
    }
}




 

参考手册

W3c0.com 提供的内容仅用于培训。我们不保证内容的正确性。通过使用本站内容随之而来的风险与本站无关。W3c0 简体中文版的所有内容仅供测试,对任何法律问题及风险不承担任何责任。 当使用本站时,代表您已接受了本站的使用条款和隐私条款。版权所有,保留一切权利。 鲁ICP备15022115号