`

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

阅读更多

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

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

1、数据库test下创建表t_flow



 

2、数据库mysql下创建t_user表



 

二、工程目录



 

三、创建类

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

 

 

 

 

 

  • 大小: 27.5 KB
  • 大小: 29.9 KB
  • 大小: 36 KB
分享到:
评论

相关推荐

    maven+springmvc+redis+mybatis整合

    4. 创建Spring配置文件,配置数据源、事务管理器、MyBatis的SqlSessionFactory等。 5. 集成Redis,配置Redis连接池,编写RedisTemplate或StringRedisTemplate的配置,实现数据缓存操作。 6. 编写Spring MVC的...

    eclipse+maven+springmvc+spring+mybatis案例附带mysql数据库

    "eclipse+maven+springmvc+spring+mybatis案例附带mysql数据库"是一个典型的Java Web开发项目,它涵盖了多个关键的技术栈,包括Eclipse IDE、Maven构建工具、Spring MVC作为MVC框架、Spring核心框架以及MyBatis持久...

    SpringMvc+Spring+Mybatis+Maven+注解方式=整合

    - MyBatis的配置文件(mybatis-config.xml)中,设置数据源和SqlSessionFactory,以便MyBatis与数据库交互。 通过以上步骤,我们可以构建一个松耦合、可测试的系统,每个组件都发挥着它应有的作用,而注解方式的...

    IDEA+MAVEN+springMVC+mybatis+mySQL+freemaker

    【标题】"IDEA+MAVEN+springMVC+mybatis+mySQL+freemaker" 涵盖了现代Web开发中的多个核心组件,这些组件共同构建了一个完整的Java Web应用程序框架。IDEA是IntelliJ IDEA,一个强大的集成开发环境,提供丰富的功能...

    Spring+SpringMVC+Mybatis+Velocity+Maven demo

    4. **配置Mybatis**:配置mybatis-config.xml,指定mapper文件的位置,以及数据源和SqlSessionFactory的配置。 5. **创建Velocity模板**:在src/main/webapp/WEB-INF/velocity目录下创建Velocity模板文件,用于渲染...

    【ssm框架】 spring+springMVC+mySQL+myBatis+freemarker+Maven小示例1

    2. `src/main/java`:存放Java源代码,包括Spring配置、Controller、Service和DAO等。 3. `src/main/resources`:存放配置文件,如Spring配置文件、MyBatis的Mapper XML文件等。 4. `src/main/webapp`:Web应用目录...

    eclipse下SpringMVC+Maven+Mybatis+MySQL项目搭建

    本项目"eclipse下SpringMVC+Maven+Mybatis+MySQL项目搭建"就是一个典型的Java Web开发实例,它利用了SpringMVC作为控制层,Maven作为项目构建工具,Mybatis作为数据持久层框架,以及MySQL作为数据库管理系统。...

    maven+spring MVC+Mybatis+jetty+mysql

    "maven+spring MVC+Mybatis+jetty+mysql" 的组合是常见的开发栈,它涵盖了项目管理、前端控制器、持久层操作、应用服务器以及数据库管理等多个层面。下面将详细介绍这些关键技术及其在实际应用中的作用。 1. Maven...

    淘淘商城网上项目学习案例springMVC+Spring+maven+mybatis+mysql.zip

    "淘淘商城网上项目学习案例springMVC+Spring+maven+mybatis+mysql.zip" 是一个集成多种技术的电子商务平台的示例项目。这个案例涵盖了Web开发中的几个关键组件,包括Spring MVC、Spring、Maven、MyBatis以及MySQL...

    maven+springMvc+MyBatis Demo

    【标题】"maven+springMvc+MyBatis Demo"是一个综合性的开发示例,它展示了如何将三个关键的Java Web开发框架——Maven、Spring MVC和MyBatis——集成到一个项目中。这个示例旨在帮助开发者理解如何在实际项目中有效...

    SSM框架整合项目(Spirng+SpringMVC+Maven+Mybatis+MySQL)

    SSM框架整合是Java开发中常见的技术栈,它由Spring、SpringMVC、Maven、Mybatis和MySQL五个核心组件组成。这个项目旨在提供一个完整的、功能完善的Web应用开发环境,便于开发者快速构建和管理Java Web应用程序。 1....

    Spirng+SpringMVC+Maven+Mybatis+MySQL项目Demo项目源码

    在实际项目中,这五者通常是这样协同工作的:用户发送HTTP请求到SpringMVC的DispatcherServlet,然后通过HandlerMapping找到对应的控制器方法,控制器方法调用Service层进行业务逻辑处理,Service层再通过Mybatis的...

    springmvc+spring+mybatis+Maven+mysql环境搭建源码

    1. `src/main/java`:存放Java源代码,包括Spring配置类、Service层、DAO层以及Controller层。 2. `src/main/resources`:存放配置文件,如Spring的applicationContext.xml、springmvc-servlet.xml,以及MyBatis的...

    spring+springmvc+mybatis+maven+mysql数据库读写分离

    在数据库读写分离中,MyBatis可以方便地配置多个数据源,从而在执行查询时选择读库,而在保存或更新数据时选择写库。 Maven是一个项目管理和综合工具,它管理项目的构建、报告和文档,依赖关系的解决,以及构建过程...

    SpringMvc+Spring+MyBatis+Maven项目

    1. **配置POM.xml**:在项目根目录下创建或编辑`pom.xml`文件,声明项目的基本信息,如groupId、artifactId、version,以及依赖的库,如Spring、SpringMvc、MyBatis和MySQL驱动等。 2. **配置Spring**:编写Spring...

    spring+springMVC+mybatis+maven+junit+mysql

    【标题】"spring+springMVC+mybatis+maven+junit+mysql" 是一个常见的Java Web项目技术栈,它涵盖了从后端开发到数据库管理,再到自动化构建和测试的完整流程。下面将详细阐述这些技术及其在项目中的作用。 ...

    Maven搭建Spring+SpringMVC+Mybatis+MySql+SpringSecurity项目源码

    项目中使用MySql存储业务数据,Mybatis与MySql的交互,通过配置文件中的数据源和映射文件来实现。 5. **Spring Security**:Spring Security是Spring生态中的安全模块,它提供了全面的安全管理功能,包括身份验证、...

    springMVC + BootStrap + mybatis + maven

    标题中的“springMVC + BootStrap + mybatis + maven”揭示了这是一个基于Java的Web应用程序开发项目,它利用了一系列流行的开源框架和技术。以下是这些技术的详细解释: 1. **Spring MVC**:Spring MVC是Spring...

    Spring+Mybatis+SpringMVC+Maven+MySql项目搭建实例.zip

    2. **配置Spring**:创建Spring的配置文件,如`applicationContext.xml`,配置Bean,包括数据源、事务管理器、Mybatis的SqlSessionFactory等。 3. **配置Mybatis**:创建Mybatis的配置文件`mybatis-config.xml`,...

Global site tag (gtag.js) - Google Analytics