springMVC+mybatis多数据源配置(dao扫描版本)

14 篇文章 0 订阅
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">原理图如下</span>

我们通过改变dao的session就可以达到数据库的切换,读写分离,多数据源就方便起来。

以下是主要配置代码

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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.test.service" />
	<context:property-placeholder location="classpath*:application.properties" />

	<import resource="classpath:spring/applicationContext-persistence.xml" />
	<import resource="classpath:spring/applicationContext-tx.xml" />
	
	<bean id="dataSourceInterceptor" class="com.test.db.DataSourceInterceptor"></bean>
	  <aop:config>  
      <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">  
           <aop:pointcut id="daoOne" expression="execution(* com.test.dao.test1.*.*(..))" />  
           <aop:pointcut id="daoTwo" expression="execution(* com.test.dao.test2.*.*(..))" />  
           <aop:before pointcut-ref="daoOne" method="setdataSourceOne" />  
           <aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" />  
       </aop:aspect>  
    </aop:config>  
	
</beans>


applicationContext-persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

	<bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="initialPoolSize" value="${c3p0.initialpoolsize}" />
		<property name="minPoolSize" value="${c3p0.minpoolsize}" />
		<property name="maxPoolSize" value="${c3p0.maxpoolsize}" />
		<property name="maxIdleTime" value="${c3p0.maxidletime}" />
		<property name="preferredTestQuery" value="select 1" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="connectionTesterClassName" value="com.mchange.v2.c3p0.impl.DefaultConnectionTester" />
		<property name="acquireIncrement" value="5" />
		<property name="maxIdleTimeExcessConnections" value="600" />
		
		<!-- 开启重连机制并设置重连次数为10 -->
		<property name="idleConnectionTestPeriod" value="60" />
		<property name="acquireRetryAttempts" value="10" />
		<property name="acquireRetryDelay" value="30000" />
		
		<property name="testConnectionOnCheckin" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
		<property name="checkoutTimeout" value="5000" />
	</bean>
	
	<bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url2}"/>
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="initialPoolSize" value="${c3p0.initialpoolsize}" />
		<property name="minPoolSize" value="${c3p0.minpoolsize}" />
		<property name="maxPoolSize" value="${c3p0.maxpoolsize}" />
		<property name="maxIdleTime" value="${c3p0.maxidletime}" />
		<property name="preferredTestQuery" value="select 1" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="connectionTesterClassName" value="com.mchange.v2.c3p0.impl.DefaultConnectionTester" />
		<property name="acquireIncrement" value="5" />
		<property name="maxIdleTimeExcessConnections" value="600" />
		
		<!-- 开启重连机制并设置重连次数为10 -->
		<property name="idleConnectionTestPeriod" value="60" />
		<property name="acquireRetryAttempts" value="10" />
		<property name="acquireRetryDelay" value="30000" />
		
		<property name="testConnectionOnCheckin" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
		<property name="checkoutTimeout" value="5000" />
	</bean>
	
	<bean id="dynamicDataSource" class="com.test.db.DynamicDataSource">  
     <property name="targetDataSources">  
           <map key-type="java.lang.String">  
             <entry value-ref="dataSourceOne" key="dataSourceOne"></entry>  
              <entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry>  
          </map>  
        </property>  
       <property name="defaultTargetDataSource" ref="dataSourceOne">  
       </property>  
    </bean>  
    
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dynamicDataSource" />
		<property name="configLocation" value="classpath:mybatis-setting.xml"></property>
		<!-- Mybatis SQL配置文件路径 -->
		<property name="mapperLocations">
			<list>
				<!-- 加载当前工程和commons工程中的映射文件 -->
				<value>classpath*:/mybatis/**/*-Mapper.xml</value>
			</list>
		</property>
	</bean>

	
	
	<!-- 扫描Dao接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描当前工程和commons工程中的DAO接口 -->
		<property name="basePackage" value="com.test.dao" />
	</bean>
	
</beans>


applicationContext-tx.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

	<!-- MyBatis依赖于jdbc事务管理 -->
	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    
          <property name="dataSource" ref="dataSourceOne" />
    </bean>     
    
    <!-- 事务拦截器配置 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
    		<tx:method name="get*" read-only="true" />
        	<tx:method name="find*" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
		</tx:attributes>
  	</tx:advice>
	
	<aop:config>    
		<!--将事务切入到Service层中-->
    	<aop:pointcut id="txAdvicePointcut" expression="execution(* com.joygame.socialservice.service.*.*(..))" /> 
    	<aop:advisor pointcut-ref="txAdvicePointcut" advice-ref="txAdvice" />
  	</aop:config>

</beans>

db核心代码

DatabaseContextHolder.java

package com.test.db;

public class DatabaseContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	public static void setCustomerType(String customerType) {
		contextHolder.set(customerType);
	}

	public static String getCustomerType() {
		return contextHolder.get();
	}

	public static void clearCustomerType() {
		contextHolder.remove();
	}
}


 

package com.test.db;

import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

@Component
public class DataSourceInterceptor {

	public void setdataSourceOne(JoinPoint jp) {
		DatabaseContextHolder.setCustomerType("dataSourceOne");
	}
	
	public void setdataSourceTwo(JoinPoint jp) {
		DatabaseContextHolder.setCustomerType("dataSourceTwo");
	}
}
package com.test.db;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType(); 
	}

}


 


测试代码

package com.test.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.test.service.TestService;

@Controller
public class TestAction {
   @Autowired
   private TestService testService;
   
   @RequestMapping(value="/test.do",method={RequestMethod.GET,RequestMethod.POST})
   public void index(){
	   testService.insert();
   }
}


package com.test.service;

public interface TestService {

	void insert();

}


package com.test.service.impl;

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

import com.test.dao.test1.TestDao;
import com.test.dao.test2.TestDao2;
import com.test.model.Test;
import com.test.service.TestService;

@Service
public class TestServiceImpl implements TestService {

	@Autowired
	private TestDao testDao;

	@Autowired
	private TestDao2 testDao2;

	public void insert() {
//		Test t = new Test();
//		t.setName("hury");
//		testDao.insert(t);
//		testDao2.insert(t);
		System.out.println(testDao.count());
		System.out.println(testDao2.count());
	}

	public TestDao getTestDao() {
		return testDao;
	}

	public TestDao2 getTestDao2() {
		return testDao2;
	}

	public void setTestDao(TestDao testDao) {
		this.testDao = testDao;
	}

	public void setTestDao2(TestDao2 testDao2) {
		this.testDao2 = testDao2;
	}

}


package com.test.model;

public final class Test {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}
}


 

package com.test.dao.test1;

import com.test.model.Test;

public interface TestDao {
	int insert(Test t);
	int count();
}


package com.test.dao.test2;

import com.test.model.Test;

public interface TestDao2 {
	int insert(Test t);
	int count();
}


<?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.test.dao.test1.TestDao">
	<insert id="insert">
		insert into test(name)
		values (#{name})
	</insert>
	<select id="count" resultType="int">
		select count(0) from test
	</select>
</mapper>


<?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.test.dao.test2.TestDao2">
	<insert id="insert">
		insert into test2(name1)
		values (#{name})
	</insert>
	<select id="count" resultType="int">
		select count(0) from test2
	</select>
</mapper>


经过以上程序;我们访问后结果http://localhost:8080/test/test.do

2
[INFO][com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] - <Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 10, acquireRetryDelay -> 30000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> true, checkoutTimeout -> 5000, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1b6171r921ffm2ghcf7zd1|5866ff, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1b6171r921ffm2ghcf7zd1|5866ff, idleConnectionTestPeriod -> 60, initialPoolSize -> 1, jdbcUrl -> jdbc:mysql://localhost:3306/test2?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 3600, maxIdleTimeExcessConnections -> 600, maxPoolSize -> 50, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, numHelperThreads -> 3, preferredTestQuery -> select 1, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> true, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]>
6


如果若要事用务,请将AOP 配置service层, DataSourceTransactionManager 注入的dataSource 就为AbstractRoutingDataSource 获取connection. 

public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}



---------

protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}

-----------------------------------------

因此可知道,这样事务就可以管理多数据源中获取到的connection, session = connection.getSession(0事务了。


对数据源重点就是通过route算法,获取connection过程

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
前段时间,分开学习了这三个框架,都是看某黄埔军校的视频,整合的部分没看视频,想自己做。 但是有一些部分自己没有能完成,主要是如何从spring容器里取出ApplicationContext,这个我的实现比较low,看了看讲义,才OK的。 我的实现: [java] view plain copy WebApplicationContext acc = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); ls = (LoginService) acc.getBean("MyService"); 而讲义上的实现: [java] view plain copy @Autowired @Qualifier("MyService") private LoginService ls; public void setLs(LoginService ls) { this.ls = ls; } 这里的区别呢,是我的实现在spring中还要注册MyService,虽然下面的写法我貌似。。。没学过?好吧应该就是注解实现。 这里放上我的Step,给自己看看,就当复习了。 [plain] view plain copy 2018年5月9日13:08:51 今天写SSM整合 1.建立项目,添加spring5\springMVC5\Mybatis3的maven 2.写spring、springmvcmybatis配置文件 2.1 spring配置文件,约束,哪里来? 源码中可以找sxd约束文件,这个的话我在 E:\2017下学期\spring-framework-5.0.5.RELEASE-dist\spring-framework-5.0.5.RELEASE\docs\spring-framework-reference 找到了,一个bean,一个context 2.2 spring配置文件,导入beans和database 2.3 spring-bean 我先创建一个实体类Person,再注册(注册了没用) 2.4 spring-db 我这里创建数据源,但是alt+/出不来提示,我一想,mysql的包没载入,在maven中加入 还是没得,恩,我加了jdbc的包,还是没有,我以为是没有源码,下载了,还是没有提示,棒 没有提示,我追了下源码,找set方法,我知道有4个,所以找得到,除此之外,还有一些其他属性可以设置 编写jdbc_mysql.properties文件,并导入 2.5 spring-bean 注册dao,这个是spring集成mybatis,注册sqlSession 这里就要导入mybatis和spring的整合包了,这里sqlsession中也要导入mybatis配置文件 2.6 spring-bean 配置mapper自动扫描 MapperScannerConfigurer将扫描basePackage所指定的包下的所有接口类(包括子类), 如果它们在SQL映射文件中定义过,则将它们动态定义为一个Spring Bean, 这样,我们在Service中就可以直接注入映射接口的bean 意思就是可以直接ref="dao类名",给你自动注册好了 2.7 写mybatis配置文件,一个别名,一个映射 约束去×××?dtd文件 2.8 写spring mvc配置文件,其实就是扫描controller 2.8 到这里,配置文件就写完了,这里注意的是,java代码没开始写,只是定义了几个包,dao\service\beans
Spring MVC是一个基于Java的框架,用于开发Web应用程序。它的优点是简化了开发过程,提供了灵活的配置和组织结构,以及强大的功能,如容易实现URL路由,请求处理和响应等。它遵循MVC(模型-视图-控制器)设计模式,将应用程序的不同层分离开来,从而提高了代码的可维护性和可测试性。 MyBatis是一个开源的持久层框架,它提供了将Java对象与关系数据库之间的映射的工具。与传统的ORM框架不同,MyBatis不依赖于JPA注解,而是通过XML或注解配置文件来描述对象与数据库的映射关系。它提供了丰富的SQL映射语言,使开发者能够更好地控制和优化SQL语句的执行。 Oracle是一个流行的关系数据库管理系统(RDBMS),它提供了可靠和高效的数据存储和管理解决方案。它支持强大的事务处理功能,并提供了广泛的SQL功能,如创建和管理表、索引、视图、存储过程等。Oracle与Spring MVC和MyBatis的集成可以通过Spring的数据访问对象(DAO)层来实现,从而实现与数据库的交互。 Spring MVC和MyBatis与Oracle的集成可以通过配置数据源、定义数据访问对象和使用事务管理器等来实现。这种集成方式可以使开发者更轻松地编写和管理数据库相关的代码,同时提供了良好的扩展性和维护性。通过将Spring MVC、MyBatis和Oracle的优势结合在一起,开发者可以更高效地开发和维护高性能和可靠的Web应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值