springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)

阅读更多

 

一、前期工作

1)开发工具Eclipse+maven+jdk1.6以上

2)Tomcat服务器

3)技术架构Spring+Mybatis

 

 

二、在eclipse一个Maven的Web工程(略)

不懂的同学请参考博客http://www.cnblogs.com/leiOOlei/p/3361633.html 

 

 

三、web.xml整合Springmvc和druid监控连接池

 

 

  
  
    Archetype Created Web Application  
      
      
        contextConfigLocation  
        classpath:spring-mybatis.xml  
      
    
      
      
        encodingFilter  
        org.springframework.web.filter.CharacterEncodingFilter  
        true  
          
            encoding  
            UTF-8  
          
      
      
        encodingFilter  
        /*  
      
    
    
		DruidWebStatFilter
		com.alibaba.druid.support.http.WebStatFilter
		
			exclusions
			*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
		
		
			sessionStatEnable
			false
		
		
			profileEnable
			true
		
	
	
		DruidWebStatFilter
		/*
	
	
      
      
        org.springframework.web.context.ContextLoaderListener  
      
      
      
        org.springframework.web.util.IntrospectorCleanupListener  
      
     
  org.springframework.web.context.ContextLoaderListener
 
  
    
  	
		DruidStatView
		com.alibaba.druid.support.http.StatViewServlet
	
	
		DruidStatView
		/druid/*
	
	
      
      
        SpringMVC  
        org.springframework.web.servlet.DispatcherServlet  
          
            contextConfigLocation  
            classpath:spring-mvc.xml  
          
        1  
        true  
      
      
        SpringMVC  
        /  
      
      
        /index.jsp  
      
  
  

 

 

 

四、Mybatis分页插件 - PageHelper

    https://github.com/pagehelper/Mybatis-PageHelper 

 

 


 

	
		
		
		
	
	
		
		
			
			
		
	

 

 

五、springmvc的xml配置

 

 



                        
    
	
	
	
	
		
			
				text/html;charset=UTF-8
			
		
	
	
	
		
			
					
			
		
	
	
	
	
	
	
		注解controller方法适配器
		
			
				
				
					
					
						
							
								
							
							WriteMapNullValue
							WriteNullStringAsEmpty
						
					
				
			
		
	
	
	
	
	
	
	

	 
	
        
        
    
    
	
	  
        
          
        
          
        
          
     



     
    
    
        
        
        
        
        
        
        

         
            
                json=application/json
                xml=application/xml
                html=text/html
            
        
        
        
    

  


    
    
 
  
    

 

 

六、Spring的AbstractRoutingDataSource实现动态数据源切换

参考博客

http://www.cnblogs.com/davidwang456/p/4318303.html

 

 

 

 



	
	
	
	
		
	
	
	
	
	
		数据库连接回调密码解密
	
	
		状态过滤器
		
		
	
	
	
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
				
			
		
		
		 
 		  
		
		
		
		
		
		
		
		
		
	



	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
				
			
		
		
		 
 		  
		
		
		
		
		
		
		
		
		
	


	
	
		数据源
		
			
				
				
				
				
			
		
		
		
		
			
				
				
				
				
			
		
	


	
	
		
		
		
		
		
		
		
	

	
	
		
		
	

	
	
		
	


	  
      
          
          
              
              
              
              
              
              
              
              
              
              
              
              
              
              
          
      
    
    
       
      
          
          
      


 七、mybatis的xml映射配置和数据库

 

 




	
		
		
		
		
	


	
		id, username, password, age
	

	
	


	


	


	


	
	
	

	
		delete from user
		where id = #{id,jdbcType=INTEGER}
	


	
		insert into user (username, password, age,typeid)
		values 
		(
			#{username,jdbcType=VARCHAR},
			#{password,jdbcType=VARCHAR},
			#{age,jdbcType=INTEGER},
			#{typeid,jdbcType=VARCHAR}
		)
	



	
		insert into user
		
			
				id,
			
			
				username,
			
			
				password,
			
			
				age,
			
			
				typeid,
			
		
		
			
				#{id,jdbcType=INTEGER},
			
			
				#{username,jdbcType=VARCHAR},
			
			
				#{password,jdbcType=VARCHAR},
			
			
				#{age,jdbcType=INTEGER},
			
			
				#{typeid,jdbcType=INTEGER},
			
		
	
	
	
	
		update user
		
			
				username = #{username,jdbcType=VARCHAR},
			
			
				password = #{password,jdbcType=VARCHAR},
			
			
				age = #{age,jdbcType=INTEGER},
			
		
		where id = #{id,jdbcType=INTEGER}
	
	
	
	
	
		update user
		set username = #{username,jdbcType=VARCHAR},
		password = #{password,jdbcType=VARCHAR},
		age = #{age,jdbcType=INTEGER}
		where id = #{id,jdbcType=INTEGER}
	



 

/*
Navicat MySQL Data Transfer

Source Server         : 127.0.0.1
Source Server Version : 50515
Source Host           : 127.0.0.1:3306
Source Database       : sm

Target Server Type    : MYSQL
Target Server Version : 50515
File Encoding         : 65001

Date: 2016-07-01 14:05:54
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for type
-- ----------------------------
DROP TABLE IF EXISTS `type`;
CREATE TABLE `type` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of type
-- ----------------------------
INSERT INTO `type` VALUES ('1', '老师');
INSERT INTO `type` VALUES ('2', '教授');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `typeid` varchar(100) DEFAULT NULL COMMENT '类型',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '周伯通', '123456', '99', '1');
INSERT INTO `user` VALUES ('2', '瑛姑', 'user', '89', '2');

 

 

 

八、项目用到的jar和maven的配置

 

	.m2\repository\junit\junit\4.11\junit-4.11.jar
	.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar
	.m2\repository\javax\javaee-api\7.0\javaee-api-7.0.jar
	.m2\repository\com\sun\mail\javax.mail\1.5.0\javax.mail-1.5.0.jar
	.m2\repository\javax\activation\activation\1.1\activation-1.1.jar
	.m2\repository\org\apache\commons\commons-lang3\3.1\commons-lang3-3.1.jar
	.m2\repository\org\springframework\spring-core\4.0.2.RELEASE\spring-core-4.0.2.RELEASE.jar
	.m2\repository\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar
	.m2\repository\org\springframework\spring-web\4.0.2.RELEASE\spring-web-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-beans\4.0.2.RELEASE\spring-beans-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-context\4.0.2.RELEASE\spring-context-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-oxm\4.0.2.RELEASE\spring-oxm-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-tx\4.0.2.RELEASE\spring-tx-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-jdbc\4.0.2.RELEASE\spring-jdbc-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-webmvc\4.0.2.RELEASE\spring-webmvc-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-expression\4.0.2.RELEASE\spring-expression-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-aop\4.0.2.RELEASE\spring-aop-4.0.2.RELEASE.jar
	.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar
	.m2\repository\org\springframework\spring-context-support\4.0.2.RELEASE\spring-context-support-4.0.2.RELEASE.jar
	.m2\repository\org\springframework\spring-test\4.0.2.RELEASE\spring-test-4.0.2.RELEASE.jar
	.m2\repository\org\mybatis\mybatis\3.2.6\mybatis-3.2.6.jar
	.m2\repository\org\mybatis\mybatis-spring\1.2.2\mybatis-spring-1.2.2.jar
	.m2\repository\mysql\mysql-connector-java\5.1.30\mysql-connector-java-5.1.30.jar
	.m2\repository\commons-dbcp\commons-dbcp\1.2.2\commons-dbcp-1.2.2.jar
	.m2\repository\commons-pool\commons-pool\1.3\commons-pool-1.3.jar
	.m2\repository\jstl\jstl\1.2\jstl-1.2.jar
	.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar
	.m2\repository\com\alibaba\fastjson\1.2.8\fastjson-1.2.8.jar
	.m2\repository\org\slf4j\slf4j-api\1.7.7\slf4j-api-1.7.7.jar
	.m2\repository\org\slf4j\slf4j-log4j12\1.7.7\slf4j-log4j12-1.7.7.jar
	.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.13\jackson-mapper-asl-1.9.13.jar
	.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.13\jackson-core-asl-1.9.13.jar
	.m2\repository\commons-fileupload\commons-fileupload\1.3.1\commons-fileupload-1.3.1.jar
	.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar
	.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar
	.m2\repository\com\github\pagehelper\pagehelper\4.1.3\pagehelper-4.1.3.jar
	.m2\repository\com\github\jsqlparser\jsqlparser\0.9.5\jsqlparser-0.9.5.jar
	.m2\repository\com\alibaba\druid\1.0.18\druid-1.0.18.jar
	.m2\repository\org\jsoup\jsoup\1.9.2\jsoup-1.9.2.jar
	.m2\repository\org\apache\velocity\velocity\1.7\velocity-1.7.jar
	.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar
	.m2\repository\commons-lang\commons-lang\2.4\commons-lang-2.4.jar
	.m2\repository\org\aspectj\aspectjrt\1.8.9\aspectjrt-1.8.9.jar
	.m2\repository\org\aspectj\aspectjweaver\1.8.9\aspectjweaver-1.8.9.jar

 


	4.0.0
	sm
	sm
	war
	0.0.1-SNAPSHOT
	M1 Maven Webapp
	http://maven.apache.org

	
		
		4.0.2.RELEASE
		
		3.2.6
		
		1.7.7
		1.2.17
	

	
		
			junit
			junit
			3.8.1
			test
		

		
			javax
			javaee-api
			7.0
		

		
			org.apache.commons
			commons-lang3
			3.1
		

		
			junit
			junit
			4.11
			
			test
		
		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-oxm
			${spring.version}
		
		
			org.springframework
			spring-tx
			${spring.version}
		

		
			org.springframework
			spring-jdbc
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		
		
			org.springframework
			spring-aop
			${spring.version}
		

		
			org.springframework
			spring-context-support
			${spring.version}
		

		
			org.springframework
			spring-test
			${spring.version}
		
		
		
			org.mybatis
			mybatis
			${mybatis.version}
		
		
		
			org.mybatis
			mybatis-spring
			1.2.2
		
		
		
			javax
			javaee-api
			7.0
		
		
		
			mysql
			mysql-connector-java
			5.1.30
		
		
		
			commons-dbcp
			commons-dbcp
			1.2.2
		
		
		
			jstl
			jstl
			1.2
		
		
		
		
			log4j
			log4j
			${log4j.version}
		


		
		
			com.alibaba
			fastjson
			1.1.41
		


		
			org.slf4j
			slf4j-api
			${slf4j.version}
		

		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
		
		
		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.13
		
		
		
			commons-fileupload
			commons-fileupload
			1.3.1
		
		
			commons-io
			commons-io
			2.4
		
		
			commons-codec
			commons-codec
			1.9
		

		
			com.github.pagehelper
			pagehelper
			4.1.3
		
		
			com.github.jsqlparser
			jsqlparser
			0.9.5
		
		
			com.alibaba
			fastjson
			1.2.8
		

		
			com.alibaba
			druid
			1.0.18
		
		
		
		
			org.jsoup
			jsoup
			1.9.2
		

		
			org.apache.velocity
			velocity
			1.7
		

			
		
			org.aspectj
			aspectjrt
			1.8.9
		
		
			org.aspectj
			aspectjweaver
			1.8.9
		
			
				
		
		    jstl
		    jstl
		    1.2
		
					
	

	
		sm
		
			
				org.apache.maven.plugins
				maven-war-plugin
				2.6
				
					false
				
			
		
	




 九、Mybatis的The SQL Builder Class的使用Service层

 

package com.flong.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.flong.BaseService;
import com.flong.dao.UserMapper;
import com.flong.pojo.entity.User;
import com.flong.pojo.vo.UserVo;
import com.flong.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

@Service
public class UserServiceImpl extends BaseService  implements UserService {

	@Autowired
	private UserMapper userMapper;

	
	
	public User getUserById(int id) {
		System.out.println(id + this.userMapper.selectId(id).getUsername());
		return this.userMapper.selectId(id);
	}

	public Boolean getLoginUser(User userLogin) {
		if (userLogin.getUsername().equals("") || (userLogin.getPassword().equals(""))) {
			return false;
		} else {

			User user = new User();
			if (this.userMapper.selectLogin(userLogin.getUsername()) != null) {
				user = userMapper.selectLogin(userLogin.getUsername());
				if (user.toString().isEmpty()) {
					return false;
				} else {
					if (user.getPassword().equals(userLogin.getPassword())) {
						return true;
					} else {
						return false;
					}
				}
			} else {
				return false;
			}
		}
	}

	public User user(User user) {
		return null;
	}

	public User selectLogin(String username) {
		return this.userMapper.selectLogin(username);
	}

	public User selectByPrimaryKey(int i) {
		return this.userMapper.selectByPrimaryKey(i);
	}

	public User getUserByusername(String username) {
		return this.userMapper.selectLogin(username);
	}

	public int inster(User user) {
		int i = this.userMapper.insert(user);
		return i;
	}

	public List list() {
		return userMapper.list();
	}

	
	
	
	/****
	 * ==============================================================通过The SQL Builder Class编写SQL进行操作数据库==================================
	 * 
	 * http://www.mybatis.org/mybatis-3/index.html
	 * @param id
	 * @return
	 */
	
	public String listBySQL() {
		 return new SQL(){
	        {
	        	 SELECT(" A.id,A.username,A.password ,B.type ")//SELECT关键字
	        	 .FROM(" user A ")//FROM关键字
	        	 .LEFT_OUTER_JOIN(" type B  on A.typeid=B.id");  //左连接
	                 
	        }}.toString();
	 
	}
	
	/**
	 * 
	 * @param user 这个是vo传值.#的字段要和vo实体一致才可以能获取到值.
	 * @return
	 */
	
	public String insertBySQL(UserVo user) {
		String sql = new SQL() 
					.INSERT_INTO("user")
				    .VALUES("username, password ,typeid,age", "#{username}, #{password},#{type},#{age}")
				    .toString();
		  return sql;
		
	}
	
	
	public String updateBySQL(UserVo user) {
		 return new SQL() {{
			    UPDATE("user");
			    SET("username = #{username}");
			    WHERE("id = #{id}");
		 }}.toString();
		
	}
	
	
	public String deleteSql(String id) {
		  return new SQL() {{
		    DELETE_FROM("user");
		    WHERE("ID = #{id}");
		  }}.toString();
	}

	
	
	
	/****
	 * ==============================================================整合pagehelper分页==================================
	 * 
	 * @param id
	 * @return
	 */
	public PageInfo query(Map params) {
		
		this.startPage(params);
		Page list = userMapper.query(params);
		return new PageInfo(list);
		
		
	}


}

 

 

 

 

十、Mybatis的The SQL Builder Class的使用Dao层

 

package com.flong.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.SelectProvider;

import com.flong.pojo.entity.User;
import com.flong.pojo.vo.UserVo;
import com.flong.service.impl.UserServiceImpl;
import com.github.pagehelper.Page;

public interface UserMapper {
	/****
	 * ==============================================================通过xml进行操作数据库==============================================================
	 * @param id
	 * @return
	 */
	
	
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    
    User selectId(int id);

	User selectLogin(String username);

	List list();
	
	
	
	/****
	 * ==============================================================通过注解和Java编写SQL进行操作数据库==============================================================
	 * @param id
	 * @return
	 */
	
	

	/**
	 * 通过mybatis的SQL方法进行查询,无xml配置的出来
	 * 告诉method = "listBySQL"方法的提供方,是来原于UserServiceImpl这个实现类里面获取的。
	 * List这个UserVo相当于是Vo
	 */
	@SelectProvider(type = UserServiceImpl.class, method = "listBySQL")
	List listBySQL();
	
	
	/**
	 * 插入
	 * @param user
	 * @return
	 */
	
	@SelectProvider(type = UserServiceImpl.class, method = "insertBySQL")
	String insertBySQL(UserVo user);
	 
	
	/**
	 * 修改
	 * @param user
	 * @return
	 */
	@SelectProvider(type = UserServiceImpl.class, method = "updateBySQL")
	String updateBySQL(UserVo user);
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@SelectProvider(type = UserServiceImpl.class, method = "deleteSql")
	String deleteSql(String id);

	
	
	
	Page query(Map params);
	 
	
	
}
 

 

 十一、spring的控制层

 

 

package com.flong.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.flong.BaseController;
import com.flong.pojo.entity.User;
import com.flong.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	
	@Resource
	private UserService userService;
	
	
	
	/**
	 * 
	 * @param request
	 * @param model
	 */
	@RequestMapping(value="/list", method = {RequestMethod.POST,RequestMethod.GET})
	public void list(HttpServletRequest request,HttpServletResponse response,Model model){
		List list=userService.list();
		writeJson(list, response);
		
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/register",method = {RequestMethod.POST,RequestMethod.GET})
	public String registerIndex(HttpServletRequest request,Model model){
		User user = new User();  
		user.setUsername("张三");  
		user.setPassword("123466");  
		user.setAge(45);  			
		user.setTypeid("2");
		this.userService.inster(user);
      
	    return "index";
	}
	

	
	
}
 

 

 

 

 

package com.flong.controller;



import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.flong.BaseController;
import com.flong.dao.UserMapper;
import com.flong.pojo.vo.UserVo;



@Controller
@RequestMapping("/user2")
public class UserController2 extends BaseController{
 
	
	@Resource
	private UserMapper userMapper;
	
	/**
	 * 查询
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/listBySQL", method = {RequestMethod.POST,RequestMethod.GET})
	public void listBySQL(HttpServletRequest request,HttpServletResponse response,Model model){
		List list=userMapper.listBySQL();
		writeJson(list, response);
	}
	
	
	
	/**
	 * 插入
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/insertBySQL", method = {RequestMethod.POST,RequestMethod.GET})
	public void insertBySQL(HttpServletRequest request,HttpServletResponse response,Model model){
		
		UserVo user = new UserVo();  
		user.setUsername("张三");  
		user.setPassword("123466");  
		user.setAge(45);  			
		user.setType("2");
		
		userMapper.insertBySQL(user);
		
		writeJson(user, response);
	}
	
	/**
	 * 修改
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/updateBySQL", method = {RequestMethod.POST,RequestMethod.GET})
	public void updateBySQL(HttpServletRequest request,HttpServletResponse response,Model model){
		UserVo user = new UserVo();  
		user.setUsername("周伯通");  
		user.setId(1);
		userMapper.updateBySQL(user);
		writeJson(user, response);
	}
	
	
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/deleteSql", method = {RequestMethod.POST,RequestMethod.GET})
	public void deleteSql(HttpServletRequest request,HttpServletResponse response,Model model){
		 String deleteSql = userMapper.deleteSql("1");
		 writeJson(deleteSql, response);
	}
	
	 
	
	
	
}

 

 

十二、利用AbstractRoutingDataSource实现动态数据源切换

package com.flong.utils.persistence;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/** 
 * 
 * 利用AbstractRoutingDataSource实现动态数据源切换
 * spring2.0以后增加了AbstractRoutingDataSource
 * 自定义一个类继承AbstractRoutingDataSource,重构一个setMethodType支持自定义开头的方法
 * 进行使用数据源的操作数据库
 */
public class DynamicChooseDataSource extends AbstractRoutingDataSource {
	public static Map> METHODTYPE = new HashMap>();

	/**
	 *  获取数据源名称
	 */
	protected Object determineCurrentLookupKey() {
		return HandleDataSource.getDataSource();
	}

	/**
	 *  设置方法名前缀对应的数据源
	 * @param map
	 */
	public void setMethodType(Map map) {
		for (String key : map.keySet()) {
			List v = new ArrayList();
			String[] types = map.get(key).split(",");
			for (String type : types) {
				if (StringUtils.isNotBlank(type)) {
					v.add(type);
				}
			}
			METHODTYPE.put(key, v);
		}
	}
}

 

package com.flong.utils.persistence;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * 切换数据源(不同方法调用不同数据源)
 */
@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DataSourceAspect {
   private static Logger logger =Logger.getLogger(DataSourceAspect.class);

	@Pointcut("execution(* com.flong.*.dao.*.*(..))")
	public void aspect() {
	}

	/**
	 * 配置前置通知,使用在方法aspect()上注册的切入点
	 */
	@Before("aspect()")
	public void before(JoinPoint point) {
		String className = point.getTarget().getClass().getName();
		String method = point.getSignature().getName();
		logger.info(className + "." + method + "(" + StringUtils.join(point.getArgs(), ",") + ")");
		try {
			for (String key : DynamicChooseDataSource.METHODTYPE.keySet()) {
				for (String type : DynamicChooseDataSource.METHODTYPE.get(key)) {
					if (method.startsWith(type)) {
						HandleDataSource.putDataSource(key);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

package com.flong.utils.persistence;

public class HandleDataSource {
	/***
	 * 数据源名称线程池
	 */
	private static final ThreadLocal holder = new ThreadLocal();

	public static void putDataSource(String datasource) {
		holder.set(datasource);
	}

	public static String getDataSource() {
		return holder.get();
	}
}

 

十三、源代码和图解

http://download.csdn.net/detail/l_ji_l/9570154 

 

 


springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第1张图片
 
springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第2张图片
 
springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第3张图片
 
springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第4张图片
 

 

 

 

 

  • springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第5张图片
  • 大小: 41.6 KB
  • springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第6张图片
  • 大小: 72.4 KB
  • springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第7张图片
  • 大小: 116.9 KB
  • springmvc+mybatis+pagehelper分页插件整合AbstractRoutingDataSource动态切换数据源(含例子代码)_第8张图片
  • 大小: 55.1 KB
  • 查看图片附件

你可能感兴趣的:(Spring,MyBatis)