Red de conocimiento informático - Material del sitio web - Cómo configurar múltiples fuentes de datos y aplicarlas usando Spring y Mybatis

Cómo configurar múltiples fuentes de datos y aplicarlas usando Spring y Mybatis

El principio básico es el siguiente

Archivo de configuración Spring para múltiples fuentes de datoslt;?xml?version="1.0"?encoding="UTF-8"?MultipleDataSource"gt;

p>

lt;property?name="defaultTargetDataSource"?ref="mySqlDataSource"/gt;

lt;property?name="targetDataSources"gt;

lt; mapgt;

lt;entry?key="mySqlDataSource"?value-ref="mySqlDataSource"/gt;

lt;entry?key="sqlServerDataSource "?value-ref= "sqlServerDataSource"/gt;

lt;/mapgt;

lt;/propertygt;

lt;/beangt;

lt ;bean?id="sqlSessionFactory"?class="org.mybatis.spring.SqlSessionFactoryBean"gt;

lt;property?name="dataSource"?ref="multipleDataSource" /gt;

lt;/beangt;

lt;! --?mybatis.spring auto-mapping?--gt;

lt;bean? class="org.mybatis .spring.mapper.MapperScannerConfigurer"gt;

lt;property?name="basePackage"?value=" com.cnblogs.lzrabbit"/gt;

lt;/beangt;

lt;;! --? Escaneo automático, múltiples paquetes de software separados por comas.

--gt;

lt; contexto: componente-scan?base-package="com.cnblogs.lzrabbit"/gt

lt;

lt;/beansgt;

applicationContext.xml

¿Paquete de implementación de múltiples fuentes de datos?com.cnblogs.lzrabbit;

¿importar? org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/** *? Creado por Rabbit el 14-5-25 */

public?MultipleDataSource extiende AbstractRoutingDataSource {< / p>

¿privado?();

público?static?void?setDataSourceKey(String?dataSource)?{

dataSourceKey.set(dataSource);

}

@Override

¿protegido?{

return?dataSourceKey.get();

}

}

¿Utilizar el método SpringAOP para cambiar automáticamente el paquete?com.cnblogs.lzrabbit;

importar?org.aspectj.lang.ProceedingJoinPoint;

¿importar? org.aspectj.lang.annotation.Around;

¿importar?

importar?org.aspectj.lang.annotation.Aspect Around;

importar?org. aspectoj.lang.annotation.Around;

importar?org.aspectj.lang.annotation.Aspect;

importar?org.springframework.stereotype.Component;

@Componente

@Aspect

público?MultipleDataSourceAspectAdvice?{

@Around("ejecución(*?com.cnblogs.lzrabbit.*.*(. ..))")

¿público?Object?doAround(ProceedingJoinPoint?jp)?throws?Throwable?{

if?(jp.getTarget()?instanceof?MySqlMapper)? {

MultipleDataSource.setDataSourceKey("mySqlDataSource");

}; else?if(jp.getTarget()?instanceof?SqlServerMapper)?{

MultipleDataSource .setDataSourceKey(

"sqlServerDataSource");

}

¿regresar?