Spring+Mybatis能不能指定多个Mybatislog4j2 指定配置文件件

相关文章推荐
1.配置两个不同的数据源,如下(由于项目使用的是druid数据库连接,配置可以会复杂点比较):...
假设现在有两个数据库myone和mytwo,读者可以理解为一个写库,一个读库,数据库中都各自有一个表,表的格式都一样,如下:
-----------------------------------...
上一篇博客说到同一个问题,经过和朋友的研究已经参考网上的资料,现在给出一份更简洁的配置。
情景:现在单个工程中需要连接两个库,这两个库在同一个mysql中,两个库都需要进行读写。
第一步:将s...
使用Mybatis连接多个数据库
直接看spring的配置吧
项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的...
开发企业应用时我们常常遇到要同时访问多种不同数据库的问题,有时是必须把数据归档到某种数据仓库中,有时是要把数据变更推送到第三方数据库中。使用Spring框架时,使用单一数据库是非常容易的,但如果要同时...
Spring+MyBatis双数据库配置
最近项目中遇到要调用其他数据库的情况,本来只使用一个MySQL数据库,但随着项目内容越来越多,逻辑越来越复杂。原来一个数据库已经不够用了,需...
数据源在配置文件中的配置
Mybatis的多条件查查询,传递参数,
第一种方法 传递map 型,
第二种方法 传递pojo
带三种方法 多个参数如果不封装成Map,就用序列号代替。
如果参数比较多且乱建议用map ...
他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)博客分类:
使用mybatis时都是用的sqlmapper来做的数据库到java对象的映射,因此在针对一些特定数据库方言使用时无法在多个数据库上切换。
解决方案:
通过定义environment的id来指定使用不同的数据库映射文件,如下
&!--WizRtf2Html Charset=0
&?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&
&environments
default="mysql"&
&environment id="mysql"&
&transactionManager
type="JDBC"
&dataSource type="POOLED"&
&property name="driver" value="com.mysql.jdbc.Driver"
&property name="url" value="jdbc:mysql://localhost:3306/test"
&property name="username" value="root"
&property name="password" value="pwd"
&/dataSource&
&/environment&
&/environments&
resource="cn/dcr/mybatis/entity/UserMapper.xml"
&/mappers&&/configuration&
方法设置方言
private void
environmentsElement(XNode context) throws
Exception { if (context != null) {if (environment == null)
environment =
context.getStringAttribute("default");
}for (XNode child :
context.getChildren()) {
String id = child.getStringAttribute("id");
dialect = id.toLowerCase();//设置方言if (isSpecifiedEnvironment(id))
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory
dsFactory = dataSourceElement(child.evalNode("dataSource"));
Environment.Builder
environmentBuilder = new
Environment.Builder(id).transactionFactory(txFactory).dataSource(dsFactory.getDataSource());
configuration.setEnvironment(environmentBuilder.build());
修改mapperElement方法
private void
mapperElement(XNode parent) throws Exception
{ if (parent != null) {for (XNode child :
parent.getChildren()) {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
InputStream
inputSif (resource
!= null && url
== null) {if(dialect !=
resource = dialect
+ "/" +//从方言指定位置查找
ErrorContext.instance().resource(resource);
inputStream
Resources.getResourceAsStream(resource);
XMLMapperBuilder
mapperParser = new
XMLMapperBuilder(inputStream, configuration, resource,
configuration.getSqlFragments());
mapperParser.parse();
else if (url
!= null &&
resource == null) {if(dialect !=
url = dialect + "/" +//从方言指定位置查找
ErrorContext.instance().resource(url);
inputStream
Resources.getUrlAsStream(url);
XMLMapperBuilder
mapperParser = new
XMLMapperBuilder(inputStream, configuration, url,
configuration.getSqlFragments());
mapperParser.parse();
else {throw new
BuilderException("A mapper element may only specify a url or
resource, but not
继承org.apache.ibatis.session.SqlSessionFactoryBuilder类创建一个新类org.apache.ibatis.session.SqlSessionFactoryBuilderEx用来加载org.apache.ibatis.builder.xml.XMLConfigBuilderEx
覆盖父类中的build方法
public SqlSessionFactory build(InputStream
inputStream, String environment, Properties props) { try {
XMLConfigBuilderEx parser = new
XMLConfigBuilderEx(inputStream, environment,
Configuration config =
parser.parse();return
build(config);
} catch (Exception
ExceptionFactory.wrapException("Error building
SqlSession.", e);
ErrorContext.instance().reset();try
inputStream.close();
} catch (IOException e) {// Intentionally ignore. Prefer previous
调用org.apache.ibatis.builder.xml.XMLConfigBuilderEx来加载配置文件
自定义mybatis配置加载Bean在spring的配置文件中添加方言的配置让自定义Bean在加载mybatis的配置时可以使用不同的数据库映射文件,如下
id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBeanEx"&
name="dataSource"
ref="dataSource" /&
&property name="configLocation"
value="classpath:configuration.xml" /&
name="mapperLocations" value="classpath*:${jdbc.dialect}/mappers/*.xml"
/& &/bean&
${jdbc.dialect}在配置文件中设置,如mysql,那么spring会把mysql/mappers下的所有映射文件加载进来
以org.mybatis.spring.SqlSessionFactoryBean为蓝本创建org.mybatis.spring.SqlSessionFactoryBeanEx类
将成员变量
private SqlSessionFactoryBuilder
sqlSessionFactoryBuilder = new
SqlSessionFactoryBuilder();
private SqlSessionFactoryBuilderEx
sqlSessionFactoryBuilderEx = new
SqlSessionFactoryBuilderEx();
并去掉setSqlSessionFactoryBuilder方法添加setSqlSessionFactoryBuilderEx方法
覆盖buildSqlSessionFactory方法
protected SqlSessionFactory buildSqlSessionFactory()
throws IOException, IllegalAccessException,
InstantiationException { XMLConfigBuilderEx
xmlConfigBuilderEx;
Configuration
if (this.configLocation !=
null) {try
xmlConfigBuilderEx = new XMLConfigBuilderEx(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration
= xmlConfigBuilderEx.parse();
} catch (Exception ex) {throw new
NestedIOException("Failed to parse config resource: "
+ this.configLocation, ex);
ErrorContext.instance().reset();
}if (this.logger.isDebugEnabled())
{this.logger.debug("Parsed configuration file: '" +
this.configLocation + "'");
} else {if (this.logger.isDebugEnabled())
{this.logger.debug("Property 'configLocation' not specified, using default MyBatis
Configuration");
configuration = new
Configuration();
}if (this.transactionFactory == null) {this.transactionFactory =
new SpringManagedTransactionFactory(this.dataSource);
Environment
environment = new
Environment(this.environment, this.transactionFactory, this.dataSource);
configuration.setEnvironment(environment);if (!ObjectUtils.isEmpty(this.mapperLocations)) {
Map&String, XNode&
sqlFragments = new
HashMap&String, XNode&();for (Resource mapperLocation : this.mapperLocations)
{if (mapperLocation == null) {continue;
}// MyBatis holds a Map using "resource" name as a
key.// If a mapper file is
loaded, it searches for a mapper// interface type.// If the type is found then it tries to load the mapper
file// again looking for
this://// String
xmlResource = type.getName().replace('.', '/') +// ".xml";//// So if a mapper
interface exists, resource cannot be an// absolute path.//
Otherwise MyBatis will throw an exception
because// it will load both a
mapper interface and the mapper xml file,// and throw an exception telling that a mapperStatement
cannot// be loaded
Sif (mapperLocation instanceof ClassPathResource)
path = ((ClassPathResource)
mapperLocation).getPath();
} else {//
this won't work if there is also a mapper interface
mapperLocation.toString();
XMLMapperBuilder
xmlMapperBuilder = new
XMLMapperBuilder(mapperLocation.getInputStream(), configuration, path,
sqlFragments);
xmlMapperBuilder.parse();
catch (Exception e)
{throw new NestedIOException("Failed to
parse mapping resource: '" + mapperLocation
ErrorContext.instance().reset();
}if (this.logger.isDebugEnabled())
{this.logger.debug("Parsed mapper
file: '" + mapperLocation + "'");
else {if (this.logger.isDebugEnabled())
{this.logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper
files specified in the config xml were
}return this.sqlSessionFactoryBuilderEx.build(configuration);
浏览 26895
浏览: 233485 次
来自: 湖北武汉
谢谢,这问题让我搞了一整天都快崩溃了。。。
让我搞了一个中午,刚开始以后是缓存问题,谢谢。。。
真的很苦B呀
没人关注你的技术,关注的是你的文采
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Spring+Mybatis 实现aop数据库读写分离与多数据库源配置操作
作者:方良棉
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Spring+Mybatis 实现aop数据库读写分离与多数据库源配置操作,需要的朋友可以参考下
在数据库层面大都采用读写分离技术,就是一个Master数据库,多个Slave数据库。Master库负责数据更新和实时数据查询,Slave库当然负责非实时数据查询。因为在实际的应用中,数据库都是读多写少(读取数据的频率高,更新数据的频率相对较少),而读取数据通常耗时比较长,占用数据库服务器的CPU较多,从而影响用户体验。我们通常的做法就是把查询从主库中抽取出来,采用多个从库,使用负载均衡,减轻每个从库的查询压力。
废话不多说,多数据源配置和主从数据配置原理一样
1、首先配置& jdbc.properties 两个数据库 A 和 B
#============ 双数据源 ======#
#----------------------A servers--------------------------#
A.driver=com.mysql.jdbc.Driver
A.url=jdbc:mysql://localhost:3619/gps4?useUnicode=true&characterEncoding=utf8
A.username=gpsadmin
A.password=1qaz&619
#----------------------B servers--------------------------#
B.driver=com.mysql.jdbc.Driver
B.url=jdbc:mysql://localhost:3619/gps6?useUnicode=true&characterEncoding=utf8
B.username=gpsadmin
B.password=1qaz&619
&2、配置 spring-mybatis.xml 文件【重要】
&!-- 引入配置文件 --&
&bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&
&property name="location" value="classpath:resources/jdbc.properties" /&
&!-- DBCP连接池 --&
&!-- &bean id="dataSource" class="mons.dbcp.BasicDataSource"
destroy-method="close"& &property name="driverClassName" value="${driver}"
/& &property name="url" value="${url}" /& &property name="username" value="${username}"
/& &property name="password" value="${password}" /& 初始化连接大小 &property name="initialSize"
value="${initialSize}"&&/property& 连接池最大数量 &property name="maxActive" value="${maxActive}"&&/property&
连接池最大空闲 &property name="maxIdle" value="${maxIdle}"&&/property& 连接池最小空闲 &property
name="minIdle" value="${minIdle}"&&/property& 获取连接最大等待时间 &property name="maxWait"
value="${maxWait}"&&/property& &/``& --&
&!-- 【重点】 A 数据源 --&
&bean name="dataSourceA" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="${A.driver}" /&
&property name="url" value="${A.url}" /&
&property name="username" value="${A.username}" /&
&property name="password" value="${A.password}" /&
&!-- 【重点】 B 数据源 --&
&bean name="dataSourceB" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="${B.driver}" /&
&property name="url" value="${B.url}" /&
&property name="username" value="${B.username}" /&
&property name="password" value="${B.password}" /&
&!--【重点】 双数据源 配合 --&
&bean id="dataSource" class="mon.database.DynamicDataSource"&
&property name="defaultTargetDataSource" ref="dataSourceB"/&
&property name="targetDataSources"&
&entry key="dataSourceA" value-ref="dataSourceA"/&
&entry key="dataSourceB" value-ref="dataSourceB"/&
&/property&
&!-- 【重点】 加入 aop 自动扫描 DataSourceAspect 配置数据库注解aop --&
&aop:aspectj-autoproxy&&/aop:aspectj-autoproxy&
&bean id="manyDataSourceAspect" class="mon.database.DataSourceAspect" /&
&aop:config&
&!-- 扫描 注解的 数据源 --&
&aop:aspect id="c" ref="manyDataSourceAspect"&
&aop:pointcut id="tx" expression="execution(* com.ifengSearch.*.dao.*.*(..))"/&
&aop:before pointcut-ref="tx" method="before"/&
&/aop:aspect&
&/aop:config&
&!-- 配置数据连接 工厂 自动扫描mapping.xml文件 --&
&bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&
&property name="dataSource" ref="dataSource"/&
&!-- 自动扫描mapping.xml文件 --&
&property name="mapperLocations" value="classpath:com/ifengSearch/*/mapping/*.xml"&&/property&
&!-- DAO接口所在包名,Spring会自动查找其下的类 --&
&bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&
&property name="basePackage" value="com.ifengSearch.*.dao" /&
&property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"&&/property&
&!-- (事务管理)transaction manager, use JtaTransactionManager for global tx 事务 --&
&bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&
&property name="dataSource" ref="dataSource" /&
3、编写几个java类动态调用数据源【重要】
  a:自定义一个注解,负责动态调用数据源
package mon.
import java.lang.annotation.*;
* 设置 数据源 注解标签的用法 写上注解标签,
* 调用相应方法切换数据源咯(就跟你设置事务一样)
* 【也可以配置 主从数据库】
* @author flm
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
public static String dataSourceA = "dataSourceA"; // A数据源
public static String dataSourceB = "dataSourceB"; // B数据源
String value();
&b、数据源的获取 Object&& aop实现 (反射)
package mon.
import java.lang.reflect.M
import org.apache.log4j.L
import org.aspectj.lang.JoinP
import org.aspectj.lang.reflect.MethodS
* 数据源的获取
* aop实现 (反射)
* @author flm
public class DataSourceAspect{
private Logger log = Logger.getLogger(DataSourceAspect.class);
public void before(JoinPoint point)
Object target = point.getTarget();// 拦截的实体类
String method = point.getSignature().getName();// 拦截的方法名称
Class&?&[] classz = target.getClass().getInterfaces();
Class&?&[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes();// 拦截的方法参数类型
Method m = classz[0].getMethod(method, parameterTypes);
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource data = m
.getAnnotation(DataSource.class);
DataSourceHolder.setDataSource(data.value());
("数据源的获取 DataSource: "+data.value());
} catch (Exception e) {
log.error("数据源的获取 aop实现 出错:"+e.getMessage());
c、DataSourceHolder& 数据源操作& 获取数据源 帮助类
package mon.
* 多数据源
* 数据源操作 获取数据源
* @author flm
public class DataSourceHolder {
//线程本地环境
private static final ThreadLocal&String& dataSources = new ThreadLocal&String&();
//设置数据源
public static void setDataSource(String customerType) {
dataSources.set(customerType);
//获取数据源
public static String getDataSource() {
return (String) dataSources.get();
//清除数据源
public static void clearDataSource() {
dataSources.remove();
d、 我们还需要实现spring的抽象类AbstractRoutingDataSource,就是实现determineCurrentLookupKey方法:
package mon.
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataS
* 多数据源
* 获取数据源(依赖于spring)
* @author flm
public class DynamicDataSource extends AbstractRoutingDataSource{
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSource();
4、接下来就可以看结果了
  我在dao层直接调用&
public interface UserDao {
* 登录判断 【数据源B】
@DataSource(value=DataSource.dataSourceB)
public List&UserBean& getLoginUserList(@Param("loginName")String loginName,@Param("loginPwd")String loginPwd);
* 查找上一级 服务商 【数据源A】
@DataSource(value=DataSource.dataSourceA)
public UserBean getServerUser(@Param("u_last_id")Integer u_last_id);
以上所述是小编给大家介绍的Spring+Mybatis 实现aop数据库读写分离与多数据库源配置操作,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具相关文章推荐
本文主要介绍如何使用spring+mybatis连接多个数据库。
同一个项目有时会涉及到多个数据库,也就是多数据源。多数据源又可以分为两种情况:
1)两个或多个数据库没有相关性,各自独立,其实这种可以作为两个项目来开发。比如在游戏开发中一个数据库是平台数据库,其...
http://blog.csdn.net/millery22/article/details/
上一篇博客说到同一个问题,经过和朋友的研究已经参考网上的资...
之前在解决一个项目连接数据库问题的时候在网上苦寻答案无果,于是显示自己研究,终于黄天不负有心,接先来我将分享一下配置的具体过程。
此种配置并非是数据库的读写分离,而是连接两个库。
情景:现在单个工程中...
1、批量新增:
view plain
"addMonthDutyIntoDB" parameterType="java.util.List"...
1、批量新增:
insert into TB_DUTY select SEQ_TB_DUTY.nextval,A.* from(
使用Mybatis连接多个数据库
spring mvc mybatis连接多个数据库
他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 mysqld 指定配置文件 的文章

 

随机推荐