Spring+MyBatis双数据库配置

                                                   Spring+MyBatis双数据库配置


    最近项目中遇到要调用其他数据库的情况,本来只使用一个MySQL数据库,但随着项目内容越来越多,逻辑越来越复杂。原来一个数据库已经不够用了,需要分库分表,所以决定扩充数据库,正好Spring可以灵活的扩充数据库。下面简单写一篇博文,记录下多数据库配置的过程。

       1.项目结构如下图:

       Spring+MyBatis双数据库配置_第1张图片

      其中mkhl和ulab分别对应两个数据库模块,同时也对应两个不同的功能模块。

      2.整个Maven项目的配置文件:pom.xml


	4.0.0

	ULAB_UsersProvider
	ULAB_UsersProvider
	0.0.1-SNAPSHOT
	jar

	ULAB_UsersProvider
	http://maven.apache.org

	
		UTF-8
		UTF-8
		4.0.0.RELEASE
		2.5.0
	

	
		
		
			junit
			junit
			4.8.1
			test
		
		
		
			javax.activation
			activation
			1.1
		
		
			commons-lang
			commons-lang
			2.6
		

		
		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-webmvc
			${spring.version}
		
		
			org.springframework
			spring-aspects
			${spring.version}
		
		
			org.springframework
			spring-context-support
			${spring.version}
		
		
			org.springframework
			spring-tx
			${spring.version}
		
		
			org.springframework
			spring-jdbc
			${spring.version}
		
		
			org.springframework
			spring-orm
			${spring.version}
		
		
			org.springframework
			spring-oxm
			${spring.version}
		

		
		
			com.alibaba
			dubbo
			2.5.3
		
		
		
		
			org.apache.zookeeper
			zookeeper
			3.4.6
		
		
			com.github.sgroschupf
			zkclient
			0.1
		

		
		
			mysql
			mysql-connector-java
			5.1.34
		
		
		
			commons-pool
			commons-pool
			1.6
		
		
			commons-dbcp
			commons-dbcp
			1.4
		

		
		
        
        
        
          com.microsoft.sqlserver
          sqljdbc4
          4.0
        

		
		
			com.alibaba
			druid
			1.0.12
		
		
			org.aspectj
			aspectjweaver
			1.8.4
		
		
		
		
			net.sf.ehcache
			ehcache-core
			2.6.10
		
		
			org.mybatis
			mybatis-ehcache
			1.0.0
		
		
		
		
			log4j
			log4j
			1.2.17
		
		
			com.googlecode.log4jdbc
			log4jdbc
			1.2
			runtime
		
		
			net.bull.javamelody
			javamelody-core
			1.50.0
		

		
		

		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.13
		
		
			com.alibaba
			fastjson
			1.2.3
		
		
			com.fasterxml.jackson.core
			jackson-annotations
			${jackson.version}
		
		
			com.fasterxml.jackson.core
			jackson-core
			${jackson.version}
		
		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson.version}
		

		
		
			org.mybatis
			mybatis
			3.2.4
		

		
		
			org.mybatis
			mybatis-spring
			1.2.2
		

		
		
		
		
		
		
		
		
		
		
			com.github.pagehelper
			pagehelper
			4.0.1
		
		
	

	
		ULAB_UsersProvider1.0
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.1
				
					1.7
					1.7
				
			

			
				org.apache.maven.plugins
				maven-shade-plugin
				1.4
				
					
						package
						
							shade
						
						
							
								
									*:*
									
										META-INF/*.SF
										META-INF/*.DSA
										META-INF/*.RSA
									
								
							
							
								
									com.ouc.ulab.main.UsersProvider
								
								
									META-INF/spring.handlers
								
								
									META-INF/spring.schemas
								
							
						
					
				
			

		

	


   3.接下来介绍与Spring和MyBatis相关的配置文件:

     1)数据库配置文件:jdbc.properties

#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc\:oracle\:thin\:@192.168.151.239\:1521\:orcl
#jdbc.username=ULab
#jdbc.password=123456
#jdbc.validationQuery=SELECT 1 FROM DUAL

jdbc.B.driverClassName=com.mysql.jdbc.Driver
jdbc.B.url=jdbc\:mysql\://110.126.70.48\:3310/ulab?useUnicode\=true&characterEncoding\=UTF-8
jdbc.B.username=mkhl
jdbc.B.password=123456

jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc\:sqlserver\://110.135.60.233\:1433;DatabaseName=OUCJiance
jdbc.username=OUCUser
jdbc.password=OUC,789

jdbc.initialSize=1
jdbc.maxActive=20
jdbc.minIdle=0
jdbc.maxWait=60000
jdbc.validationQuery=SELECT 1
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.testWhileIdle=true
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=25200000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true
jdbc.filters=stat

     2)ehcache缓存配置:ehcache.xml

 
 
 
          
 

    3)日志配置:log4j.properties

log4j.rootLogger=INFO,stdout,logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=D:/log4j/U-LAB/usersProvide_log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %-5p [%t] %c.%M(%L) - %m%n
  
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout

log4j.logger.jdbc.sqlonly=OFF
log4j.logger.jdbc.sqltiming=OFF
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.connection=OFF

    4)mybatis基础配置:mybatis-configure.xml

   
   
   
    
 	 
 	 
    
   

    5)数据库连接池Druid配置:spring-druid.xml


   

	
	

	
		
			
				com.ouc.ulab.service.*
				com.ouc.mkhl.service.*
			
		
	
	
		
	


    6)MyBatis数据库相关的配置,双数据库配置主要内容在这里:spring-mybatis.xml




	
	
		
		
		
		

		
		
		
		
		
		
		
		

		
		
		
		

		
		
		
		

		
		
		
		
		
		

		
		
	

    
	
		
		
		
		

		
		
		
		
		
		
		
		

		
		
		
		

		
		
		
		

		
		
		
		
		
		

		
		
	
	
	
	
		
		
		
		
			
				
					
						
							dialect=sqlserver
						
					
				
			
		
		
	
    
    
		
		
		
		
	

	
		
		
	

    
		
		
	
	
	
	
		
	


    7)Spring中Bean的注解扫描识别配置:spring.xml,此处为了发布Dubbo服务。



    
    
    
	
	
	
	
	
	
	
	

    8)发布Dubbo接口配置:spring-dubbo.xml,此处配置注册中心地址,发布接口等内容。




	
	

	

	

    
	
	
	
	
	
	
	


    4.以下以ulab模块为例,介绍相关的功能包:dao,model,mapping,service,service.impl,main。

       1)model数据库表实体类包:VSupplyUser类

package com.ouc.ulab.model;

import java.io.Serializable;

public class VSupplyUser implements Serializable {
	
    private static final long serialVersionUID = 12L;
	
    private String supplycode;

    private String supplyname;

    private String supplypass;

    public String getSupplycode() {
        return supplycode;
    }

    public void setSupplycode(String supplycode) {
        this.supplycode = supplycode == null ? null : supplycode.trim();
    }

    public String getSupplyname() {
        return supplyname;
    }

    public void setSupplyname(String supplyname) {
        this.supplyname = supplyname == null ? null : supplyname.trim();
    }

    public String getSupplypass() {
        return supplypass;
    }

    public void setSupplypass(String supplypass) {
        this.supplypass = supplypass == null ? null : supplypass.trim();
    }
}

     2)数据接口Dao包:VSupplyUserMapper

package com.ouc.ulab.dao;

import java.util.List;

import com.ouc.ulab.model.VSupplyUser;

public interface VSupplyUserMapper {
    
    int insert(VSupplyUser record);

    int insertSelective(VSupplyUser record);
    
    public VSupplyUser getVSupplyUserByCode(String supplycode);
    
    public List  getAllVSupplyUser();
    
}

     3)SQL语句配置包:VSupplyUserMapper.xml




  
    
    
    
  
  
  
  
  
  
  
    insert into V_SupplyUser (SupplyCode, SupplyName, SupplyPass
      )
    values (#{supplycode,jdbcType=NVARCHAR}, #{supplyname,jdbcType=NVARCHAR}, #{supplypass,jdbcType=NVARCHAR}
      )
  
  
    insert into V_SupplyUser
    
      
        SupplyCode,
      
      
        SupplyName,
      
      
        SupplyPass,
      
    
    
      
        #{supplycode,jdbcType=NVARCHAR},
      
      
        #{supplyname,jdbcType=NVARCHAR},
      
      
        #{supplypass,jdbcType=NVARCHAR},
      
    
  

    4)Dubbo服务接口包:VSupplierUsersService

package com.ouc.ulab.service;

import java.util.List;

import com.ouc.ulab.model.VSupplyUser;

public interface VSupplierUsersService {
	
	public VSupplyUser getVSupplyUserByCode(String supplycode);
	
	public List  getAllVSupplyUser();
}

    5)Dubbo服务接口具体实现包:VSupplierUsersSerImpl

package com.ouc.ulab.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ouc.ulab.dao.VSupplyUserMapper;
import com.ouc.ulab.model.VSupplyUser;
import com.ouc.ulab.service.VSupplierUsersService;

@Service("vSupplierUsersService")
public class VSupplierUsersSerImpl implements VSupplierUsersService{
	
	@Autowired  VSupplyUserMapper vSuppUserMapper;

	@Override
	public VSupplyUser getVSupplyUserByCode(String supplycode){
	     return vSuppUserMapper.getVSupplyUserByCode(supplycode);
	}
	
	@Override
	public List  getAllVSupplyUser(){
	    return vSuppUserMapper.getAllVSupplyUser();
	}
}

     5.发布接口测试Main:UsersProvider

package com.ouc.ulab.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ouc.ulab.service.VSupplierUsersService;
import com.ouc.ulab.model.VSupplyUser;
import com.ouc.mkhl.service.UsersEvaluateService;
import com.ouc.mkhl.model.PlanCount;

public class UsersProvider {

    private static VSupplierUsersService vSuppUsersSer;

    private static UsersEvaluateService usersEvaluateSer;
    
    @Autowired
    public static void main(String[] args) throws Exception {
	try {
	    @SuppressWarnings("resource")
	    ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext(
		    new String[] { "classpath:spring.xml",
			    "classpath:spring-mybatis.xml",
			    "classpath:spring-dubbo.xml" });

	    cxt.start();

	    vSuppUsersSer = (VSupplierUsersService) cxt
		    .getBean("vSupplierUsersService");

	    String supplyCode = "V98758";
	    VSupplyUser user = vSuppUsersSer.getVSupplyUserByCode(supplyCode);
	    System.out.println("供应商用户信息:");
	    System.out.println("V码:" + user.getSupplycode());
	    System.out.println("供应商名称:" + user.getSupplyname());
	    System.out.println("供应商登录密码:" + user.getSupplypass());
            
	    List supplyUserList = new ArrayList();
	    supplyUserList = vSuppUsersSer.getAllVSupplyUser();
	    System.out.println("供应商用户总量:"+supplyUserList.size());
	    
	 
	    usersEvaluateSer = (UsersEvaluateService) cxt.getBean("usersEvaluateService");
	    List planCountList = new ArrayList();
	    planCountList = usersEvaluateSer.getPlanCountByYearAndVCode("2016", "V13187");
	    System.out.println("问题方案统计结果:" + planCountList.size());
		
	    PlanCount planCount = new PlanCount();
	    planCount = usersEvaluateSer.getPlanCountByYearAndMonthAndVCode("2016", "V13187", 4);
	    System.out.println("问题方案:" + planCount.getPlanNum() + planCount.getQuestionNum());
	    
	    System.in.read(); // 模拟开启

	} catch (Exception e) {
	    e.printStackTrace();
	    System.out.println(e.getMessage());
	    Logger log = Logger.getLogger(UsersProvider.class);
	    log.error(e.getMessage()); // 将异常输出到文件
	}

    }
}

     6.运行结果如下图:

    Spring+MyBatis双数据库配置_第2张图片

    

    以上数据库分库已经大功告成,以后在与大家详细介绍如何分表,以及分表的原则。

    文章中如有错误,欢迎高手指正,本人是一个小菜鸟,正在努力学习中。


你可能感兴趣的:(软件架构,JavaWeb开发框架,Java,Spring开源框架整合)