天天看点

(已解决)springMVC + maven + mybatis + mysql在service层配置多数据源

IDEA + springMVC + mybatis +mysql功能下配置多数据源,已完成测试。本例是参照一位高手的例子工程如下:

一、数据库:均为mysql数据库

1、数据库test下创建表t_flow

(已解决)springMVC + maven + mybatis + mysql在service层配置多数据源

2、数据库mysql下创建t_user表

(已解决)springMVC + maven + mybatis + mysql在service层配置多数据源

二、工程目录

(已解决)springMVC + maven + mybatis + mysql在service层配置多数据源

三、创建类

1、User.java  

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3547683104555927953L;

	private Integer id;

	private String userName;

	private String password;

	private Integer roleId;

	private String trueName;

	private Date createTime;

	private Date modifyTime;

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @return the userName
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @return the roleId
	 */
	public Integer getRoleId() {
		return roleId;
	}

	/**
	 * @return the trueName
	 */
	public String getTrueName() {
		return trueName;
	}

	/**
	 * @return the createTime
	 */
	public Date getCreateTime() {
		return createTime;
	}

	/**
	 * @return the modifyTime
	 */
	public Date getModifyTime() {
		return modifyTime;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @param userName the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @param roleId the roleId to set
	 */
	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}

	/**
	 * @param trueName the trueName to set
	 */
	public void setTrueName(String trueName) {
		this.trueName = trueName;
	}

	/**
	 * @param createTime the createTime to set
	 */
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	/**
	 * @param modifyTime the modifyTime to set
	 */
	public void setModifyTime(Date modifyTime) {
		this.modifyTime = modifyTime;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", roleId=" + roleId
				+ ", trueName=" + trueName + ", createTime=" + createTime + ", modifyTime=" + modifyTime + "]";
	}

}
           

2、Flow.java

public class Flow {

	private String id;

	/**
	 * 投保主键ID(UUID)
	 */
	private String insuranceId;

	/**
	 * 节点代码
	 */
	private String codeId;

	/**
	 * 操作时间
	 */
	private Date operatingTime;

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @return the insuranceId
	 */
	public String getInsuranceId() {
		return insuranceId;
	}

	/**
	 * @return the codeId
	 */
	public String getCodeId() {
		return codeId;
	}

	/**
	 * @return the operatingTime
	 */
	public Date getOperatingTime() {
		return operatingTime;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @param insuranceId the insuranceId to set
	 */
	public void setInsuranceId(String insuranceId) {
		this.insuranceId = insuranceId;
	}

	/**
	 * @param codeId the codeId to set
	 */
	public void setCodeId(String codeId) {
		this.codeId = codeId;
	}

	/**
	 * @param operatingTime the operatingTime to set
	 */
	public void setOperatingTime(Date operatingTime) {
		this.operatingTime = operatingTime;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Flow [id=" + id + ", insuranceId=" + insuranceId + ", codeId=" + codeId + ", operatingTime="
				+ operatingTime + "]";
	}

}
           

3、UserMapper.java

@Repository(value="UserMapper")
public interface UserMapper {

	/**
	 * @param id
	 * @return
	 */
	public User get(Integer id);

	/**
	 * @param id
	 * @return
	 */
	public User get2(Integer id);

	/**
	 * @return
	 */
	public List<User> findAll();

	/**
	 * @param user
	 */
	public void insert(User user);
}
           

4、FlowMapper.java

@Repository(value="FlowMapper")
public interface FlowMapper {

	/**
	 * @param id
	 * @return
	 */
	public Flow get(String id);

}
           

5、BaseMySqlService.java   。注意:这个类默认通过@Transactional(value="isap")的注解形式注入了配置了数据源,可以通过查看applicationContext.xml查看配置的数据源。

@Transactional(value = "isap", rollbackFor = Exception.class)
public abstract class BaseMySqlService {

}
           

6、UserService.java   。这个类继承了BaseMySqlService类,所以这个类默认的数据源就是@Transactional(value="isap")

@Service("userService")
//@Transactional(value = "isap", rollbackFor = Exception.class)
public class UserService extends BaseMySqlService {

	@Autowired
	private UserMapper userMapper;

	/**
	 * @param id
	 * @return
	 */
	public User get(Integer id) {
		return userMapper.get(id);
	}

	/**
	 * @param id
	 * @return
	 */
	public User get2(Integer id) {
		return userMapper.get2(id);
	}

	/**
	 * @return
	 */
	public List<User> findAll() {
		return userMapper.findAll();
	}

	/**
	 * @param user
	 * @throws Exception 
	 */
	public void insert(User user) throws Exception {
		userMapper.insert(user);
		throw new Exception("testException");
	}
}
           

7、FlowService.java    。这个类配置了自己的数据源

@Service("flowService")
@Transactional(value = "insurance", rollbackFor = Exception.class)
public class FlowService {

	@Autowired
	private FlowMapper flowMapper;

	/**
	 * @param id
	 * @return
	 */
	public Flow get(String id) {
		return flowMapper.get(id);
	}

}
           

8、init-config.properties数据库配置文件 

#\u6570\u636e\u5e93\u8fde\u63a5\u6c60\u8bbe\u7f6e
dataSource2.driver=com.mysql.jdbc.Driver
dataSource2.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
dataSource2.username=root
dataSource2.password=admin

#dataSource2.driver=oracle.jdbc.driver.OracleDriver
#dataSource2.url=jdbc:oracle:thin:@192.168.10.43:1521:insurance
#dataSource2.username=insurance
#dataSource2.password=Insurancetest

dataSource.driver=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://172.16.10.43:3306/mysql?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
dataSource.username=root
dataSource.password=admin
           

9、applicationContext.xml配置文件

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd">

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:init-config.properties</value>
		</property>
	</bean>
	
	<!-- enable component scanning (beware that this does not enable mapper scanning!) -->
	<context:component-scan base-package="mybatis" />

	<!-- enable autowire -->
	<context:annotation-config />

	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${dataSource.url}" />
		<property name="username" value="${dataSource.username}" />
		<property name="password" value="${dataSource.password}" />
		<property name="connectionProperties" value="${dataSource.driver}"></property>

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />
		<property name="maxActive" value="20" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="validationQuery" value="SELECT 'x'" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>

	<!-- define the SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="mybatis.domain" />
		<property name="mapperLocations" value="classpath:mapping/*.xml" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
		<property name="basePackage" value="mybatis.mapper" />
	</bean>

	<!-- transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
		<qualifier value="isap" />
	</bean>

	<!-- 全注解方式   需加上@Transactional -->
	<tx:annotation-driven transaction-manager="transactionManager" />

	<!-- =================================================================== -->
	<!-- 数据源2 -->
	<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${dataSource2.url}" />
		<property name="username" value="${dataSource2.username}" />
		<property name="password" value="${dataSource2.password}" />
		<property name="connectionProperties" value="${dataSource2.driver}"></property>

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />
		<property name="maxActive" value="20" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="validationQuery" value="SELECT 'x'" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>
	
	<bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource2" />
		<property name="typeAliasesPackage" value="mybatis.domain2" />
		<property name="mapperLocations" value="classpath:mappings/*.xml" />

	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"/>
		<property name="basePackage" value="mybatis.mapper2" />
	</bean>
	
	<bean id="transactionManager2"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource2" />
		<qualifier value="insurance" />
	</bean>

	<!-- 全注解方式 -->
	<tx:annotation-driven transaction-manager="transactionManager2" />

	<task:annotation-driven/>

</beans>
      

四、测试类 MultiTest.java

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class MultiTest {

	/**
	 * @param
	 * @throws Exception 
	 */

	public static void main(String[] args) throws Exception {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		System.out.println(userService.get(11));
		System.out.println(userService.get2(22));

		FlowService flowService = (FlowService) ac.getBean("flowService");
		System.out.println(flowService.get("2"));
	}
}
           

测试结果:

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get - ==>  Preparing: SELECT * from t_user where id = ?

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get - ==> Parameters: 11(Integer)

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get - <==      Total: 1

User [id=11, userName=null, password=11, roleId=null, trueName=null, createTime=null, modifyTime=null]

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get2 - ==>  Preparing: SELECT * from t_user where id = ?

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get2 - ==> Parameters: 22(Integer)

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper.UserMapper.get2 - <==      Total: 1

User [id=22, userName=22, password=22, roleId=22, trueName=22, createTime=Thu Mar 02 00:00:00 CST 2017, modifyTime=Thu Mar 02 00:00:00 CST 2017]

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper2.FlowMapper.get - ==>  Preparing: SELECT * from t_flow where ID = ?

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper2.FlowMapper.get - ==> Parameters: 2(String)

2017-03-30 19:34:40 [main] DEBUG mybatis.mapper2.FlowMapper.get - <==      Total: 1

Flow [id=2, insuranceId=233333, codeId=23333, operatingTime=Mon Mar 27 00:00:00 CST 2017]

五、最后附上原文章参考链接,只是原文这个例子直接运行未成功

http://zhuchengzzcc.iteye.com/blog/1827633