mapper:.....存放XXMapper以及实体类的对应表的关系的xml文件
public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDbType(String dbType) { contextHolder.set(dbType); } public static String getDbType() { return ((String) contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); } }
import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder. getDbType(); } }
<?xml version="1.0" encoding= "UTF-8"?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "http://www.springframework.org/schema/context" xmlns:mvc= "http://www.springframework.org/schema/mvc" xsi:schemaLocation= "http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 注解扫描器 --> <context:component-scan base-package ="com.baimi.routerweb"/> <!-- 配置试图解析器 --> <bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name ="prefix" value="/"></ property> <property name ="suffix" value=".jsp"></ property> </bean > <import resource ="classpath:beans.xml"/> </beans>
<context:component-scan base-package ="com" /> <!-- 多数据源配置 --> <bean id ="ds_admin" class= "org.apache.commons.dbcp.BasicDataSource" > <property name ="driverClassName" value= "com.mysql.jdbc.Driver"></property > <property name ="url" value= "jdbc:mysql://192.168.19.72:3307/100msh_admin" ></property > <property name ="username" value="root"></ property> <property name ="password" value="root"></ property> </bean > <bean id ="ds_partner" class= "org.apache.commons.dbcp.BasicDataSource" > <property name ="driverClassName" value= "com.mysql.jdbc.Driver"></property > <property name ="url" value= "jdbc:mysql://192.168.19.72:3308/100msh_partner" ></property > <property name ="username" value="root"></ property> <property name ="password" value="root"></ property> </bean > <bean id ="ds_mop" class="org.apache.commons.dbcp.BasicDataSource"> <property name ="driverClassName" value= "com.mysql.jdbc.Driver"></property > <property name ="url" value= "jdbc:mysql://192.168.19.72:3309/100msh_mop" ></property > <property name ="username" value="root"></ property> <property name ="password" value="root"></ property> </bean > <!-- 动态配置数据源 --> <bean id ="dataSource" class= "com.baimi.routerweb.datasource.DynamicDataSource" > <property name ="targetDataSources"> <map key-type ="java.lang.String"> <entry value-ref ="ds_admin" key= "ds_admin"></entry > <entry value-ref ="ds_partner" key= "ds_partner"></entry > <entry value-ref ="ds_mop" key="ds_mop"></ entry> </map > </property > <property name ="defaultTargetDataSource" ref= "ds_mop"></property > <!-- 默认使用ds1的数据源 --> </bean >
<!-- 创建SqlSessionFactory --> <bean id ="sqlSessionFactoryBean" class= "org.mybatis.spring.SqlSessionFactoryBean" > <!-- 指定数据源 --> <property name ="dataSource" ref="dataSource" /> <!-- 指定mybatis 的配置文件 --> <property name ="configLocation" value= "classpath:mybatis-config.xml" /> </bean >
<!-- 配置事务 --> <bean id ="transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name ="dataSource" ref="dataSource"></ property> </bean > <!-- 映射接口 --> <bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name ="basePackage" value= "com.baimi.routerweb.mapper"></property > </bean > <!-- 配置事务的传播特性 --> <tx:advice id ="txAdvice" transaction-manager="transactionManager"> <tx:attributes > <tx:method name ="find*" read-only="true" /> <tx:method name ="get*" read-only="true" /> <tx:method name ="query*" read-only="true" /> <tx:method name ="add*" propagation="REQUIRED" /> <tx:method name ="update*" propagation="REQUIRED" /> <tx:method name ="del*" propagation="REQUIRED" /> </tx:attributes > </tx:advice >
<!-- 配置AOP --> <aop:config > <!-- 切点 --> <aop:pointcut expression ="execution(* com.baimi.routerweb.service..*.*(..))" id= "pointcut" /> <aop:advisor advice-ref ="txAdvice" pointcut-ref="pointcut" /> </aop:config >
public class User { private int userId; private int compId; private String euserName; private String euserPhone; private int euserStatus; private String eAddTime; private String eLeaveTime; private String eUserNameCn; private int cUserId; private String scDown; private String userDesc; public int getUserId() { return userId; } public void setUserId( int userId) { this. userId = userId; } public int getCompId() { return compId; } public void setCompId( int compId) { this. compId = compId; } public String getEuserName() { return euserName; } public void setEuserName(String euserName) { this. euserName = euserName; } public String getEuserPhone() { return euserPhone; } public void setEuserPhone(String euserPhone) { this. euserPhone = euserPhone; } public int getEuserStatus() { return euserStatus; } public void setEuserStatus( int euserStatus) { this. euserStatus = euserStatus; } public String geteAddTime() { return eAddTime; } public void seteAddTime(String eAddTime) { this. eAddTime = eAddTime; } public String geteLeaveTime() { return eLeaveTime; } public void seteLeaveTime(String eLeaveTime) { this. eLeaveTime = eLeaveTime; } public String geteUserNameCn() { return eUserNameCn; } public void seteUserNameCn(String eUserNameCn) { this. eUserNameCn = eUserNameCn; } public int getcUserId() { return cUserId; } public void setcUserId( int cUserId) { this. cUserId = cUserId; } public String getScDown() { return scDown; } public void setScDown(String scDown) { this. scDown = scDown; } public String getUserDesc() { return userDesc; } public void setUserDesc(String userDesc) { this. userDesc = userDesc; } }
public interface UserMapper { public User getUser(String euserPhone); }
<?xml version="1.0" encoding= "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace= "com.baimi.routerweb.mapper.UserMapper" > <resultMap type ="User" id="usermap"> <result property ="userId" column="euser_id" /> <result property ="compId" column="comp_id" /> <result property ="euserName" column="euser_name" /> <result property ="euserPhone" column="euser_phone" /> <result property ="euserStatus" column="euser_status" /> <result property ="eAddTime" column="e_add_time" /> <result property ="eLeaveTime" column="e_leave_time" /> <result property ="eUserNameCn" column="euser_name_cn" /> <result property ="cUserId" column="user_id" /> <result property ="scDown" column="sc_own" /> <result property ="userDesc" column="euser_desc" /> </resultMap > <!-- 查询一条记录 --> <select id ="getUser" parameterType="java.lang.String" resultMap= "usermap"> select * from t_expand_user where euser_phone=#{euserPhone} </select > </mapper>
<?xml version="1.0" encoding= "UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <!-- 别名 --> <typeAliases > <typeAlias type ="com.baimi.routerweb.entity.User" alias= "User" /> </typeAliases > <mappers > <mapper resource ="com/baimi/routerweb/mapper/User.xml" /> </mappers > </configuration>
public interface UserService { public User getUser(String euserPhone); }
import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.baimi.routerweb.datasource.DataSourceContextHolder; import com.baimi.routerweb.datasource.DataSourceType; import com.baimi.routerweb.entity.User; import com.baimi.routerweb.mapper.UserMapper; import com.baimi.routerweb.service.UserService; @Service public class UserServiceImpl implements UserService { @Resource(name = "userMapper") private UserMapper userMapper; @Override public User getUser(String euserPhone) { DataSourceContextHolder. setDbType(DataSourceType.SOURCE_MOP); return userMapper.getUser(euserPhone); } }
//切换数据库 DataSourceContextHolder. setDbType(DataSourceType. SOURCE_MOP); //从数据库中得到该用户的数据 User user= userService.getUser(userId);
import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.baimi.routerweb.common.Constant; import com.baimi.routerweb.common.ErrorHandle; import com.baimi.routerweb.datasource.DataSourceContextHolder; import com.baimi.routerweb.datasource.DataSourceType; import com.baimi.routerweb.entity.User; import com.baimi.routerweb.service.UserService; import com.baimi.routerweb.util.HttpUtil; @Controller public class MainController { @Resource(name = "userServiceImpl") private UserService userService; @RequestMapping("/login.do") public String login(HttpServletRequest request, HttpServletResponse response) { // 获取客户端传过来的code的值 String code = request.getParameter( "code"); if (code == null || "".equals(code)) { return ErrorHandle.getError(ErrorHandle.INVALID_TOKEN, "invalid token"); } // 从微信得到token的值 JSONObject objToken = HttpUtil.httpRequest(Constant.URL_WEIXIN_TOKEN, "GET", null); if (objToken == null || "".equals(objToken)) { return ErrorHandle.getError(ErrorHandle.SERVICE_UNRESPONSE, "service unresponse"); } if (!objToken.has( "access_token")) { return ErrorHandle.getError(ErrorHandle.INVALID_TOKEN, "invalid token"); } //根据token和code得到UserId JSONObject objUser = HttpUtil.httpRequest(Constant.URL_GET_USERID, "POST", "access_token=" + objToken.getString("access_token" )+ "&code=" + code + "&agentid=1"); if(objUser== null|| "".equals(objUser)){ return ErrorHandle.getError(ErrorHandle.SERVICE_UNRESPONSE, "service unresponse"); } if(!objUser.has( "UserId")){ return ErrorHandle.getError(ErrorHandle.INVALID_TOKEN, "invalid token"); } String userId=objUser.getString( "UserId"); //切换数据库 DataSourceContextHolder. setDbType(DataSourceType.SOURCE_MOP); //从数据库中得到该用户的数据 User user= userService.getUser(userId); if(user!= null){ JSONObject rtObj = new JSONObject(); rtObj.put( "userId", String.valueOf(user.getUserId())); return rtObj.toString(); } return ErrorHandle.getError(ErrorHandle.INVALID_USER,"invalid user"); } }