当前位置:网站首页>Configure multiple database connections using the SSM framework
Configure multiple database connections using the SSM framework
2022-06-28 05:59:00 【Coder without code】
Company requirements , You need to use two databases , One mysql, One oracle. So you need to configure two databases to operate .
1. First , Need to be in jdbc.properties Write the configuration data of the two libraries in the file , But one wrote driver, The other wrote driver2, Distinguish the variable names of the two libraries .
The code is as follows :
#oracle web
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.3.4:1521:ORCL
jdbc.username=abc
jdbc.password=adasdsa
#mysql
jdbc.driver2=com.mysql.jdbc.Driver
jdbc.url2=jdbc:mysql://192.168.3.4:3306/logcount?useUnicode=true&characterEncoding=utf-8
jdbc.username2=root
jdbc.password2=12345652. stay spring-mybatis.xml Configuration in :
- Start annotation mode first
- The two databases are configured differently id Of DataSource
- Is the path to configure the user-defined class for switching databases , Select the default database .
- To configure aop Intercept dao All access interfaces of the layer , stay dao Layer annotation changes the database .
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<!-- Open annotation mode -->
<context:annotation-config />
<context:component-scan base-package="com.shiyanlou" />
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- oracle database -->
<bean id="dataSource_first"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- sqlite database -->
<bean id="dateSource_second"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver2}" />
<property name="url" value="${jdbc.url2}" />
<property name="username" value="${jdbc.username2}" />
<property name="password" value="${jdbc.password2}" />
</bean>
<!-- The following is a custom class for switching databases -->
<bean id="dataSource" class="com.shiyanlou.util.MultipleDataSource">
<!-- By default sqlite database -->
<property name="defaultTargetDataSource" ref="dateSource_second"></property>
<property name="targetDataSources">
<map>
<entry key="dataSource_first" value-ref="dataSource_first"></entry>
<entry key="dateSource_second" value-ref="dateSource_second"></entry>
</map>
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:/mappers/*.xml"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.shiyanlou.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory">
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<!-- section -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="dataSourceAspect" class="com.shiyanlou.util.DataSourceAspect"></bean>
<aop:config>
<aop:aspect ref="dataSourceAspect">
<!-- Intercept all service Method , stay dao Add annotation to layer -->
<aop:pointcut expression="execution(* com.shiyanlou.dao..*.*(..))" id="dataSourcePointcut"/>
<aop:before method="intercept" pointcut-ref="dataSourcePointcut"/>
</aop:aspect>
</aop:config>
</beans>3. Tool class configuration : Custom annotation
- Annotation class DataSource.java
/**
* <p>Title: DataSource.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author Lin Meng
* @date 2018 year 5 month 3 Japan
* @version 1.0
*/
package com.shiyanlou.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author linmeng
*
*/
/* @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource{
String value();
}
- Annotation class DataSourceAspect.java
/**
* <p>Title: DataSourceAspect.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author Lin Meng
* @date 2018 year 5 month 3 Japan
* @version 1.0
*/
package com.shiyanlou.util;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
/**
* @author linmeng
*
*/
public class DataSourceAspect{
// Method of intercepting target , Get by @DataSource The specified data source id , Set to the thread store to switch data sources
public void intercept(JoinPoint point) throws Exception{
Class<?> target = point.getTarget().getClass();
MethodSignature signature=(MethodSignature)point.getSignature();
// Annotation of target type is used by default , If not, use the annotation of its implementation interface
for (Class<?> clazz : target.getInterfaces()) {
resolveDataSource(clazz, signature.getMethod());
}
resolveDataSource(target, signature.getMethod());
}
/**
* Extract the data source identification in the target object method annotation and type annotation
*/
public void resolveDataSource(Class<?>clazz,Method method) {
try {
Class<?>[]types=method.getParameterTypes();
// Type annotation is used by default
if (clazz.isAnnotationPresent(DataSource.class)) {
DataSource source = clazz.getAnnotation(DataSource.class);
DbContextHolder.setDataSource(source.value());
}
// Method annotations can override type annotations
Method m=clazz.getMethod(method.getName(), types);
if (m!=null && m.isAnnotationPresent(DataSource.class)) {
DataSource source = m.getAnnotation(DataSource.class);
DbContextHolder.setDataSource(source.value());
}
} catch (Exception e) {
System.out.println(clazz+":"+e.getMessage());
}
}
}
- Switch the tool class of the database DbContextHolder.java:
/**
* <p>Title: DbContextHolder.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author Lin Meng
* @date 2018 year 5 month 2 Japan
* @version 1.0
*/
package com.shiyanlou.util;
/**
* @author linmeng
* Tool class for switching data sources
*/
public class DbContextHolder {
private static final ThreadLocal<String>THREAD_DATA_SOURCE =new ThreadLocal<>();
/**
* Set the current database
*/
public static void setDataSource(String dataSource) {
THREAD_DATA_SOURCE.set(dataSource);
}
/**
* Get the current database
*/
public static String getDataSource() {
return THREAD_DATA_SOURCE.get();
}
/**
* Clear context data
*/
public static void clearDataSource() {
THREAD_DATA_SOURCE.remove();
}
}
Custom database switching class :
/**
* <p>Title: MultipleDataSource.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author Lin Meng
* @date 2018 year 5 month 2 Japan
* @version 1.0
*/
package com.shiyanlou.util;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @author linmeng
* Custom database switching class
*/
public class MultipleDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return DbContextHolder.getDataSource();
}
}
Only this and nothing more , The database configuration is complete , It is very convenient to use , If two databases are configured , There is a default database , There is no need to modify , When you need to use another database , Only need dao Add an annotation to the layer :
/**
* <p>Title: CityDao.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author Lin Meng
* @date 2018 year 5 month 4 Japan
* @version 1.0
*/
package com.shiyanlou.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.shiyanlou.domain.CityInfo;
import com.shiyanlou.util.DataSource;
/**
* @author linmeng
*
*/
@DataSource(value="dataSource_first")
public interface CityDao {
public List<CityInfo>getAdInfo(@Param("city")String city);
public Integer getAdInfoCount(String city);
public List<CityInfo>getCityInfo(Map<String, Object>map);
public List<CityInfo>getPoiData(Map<String, Object>map);
public Integer getCityInfoCount(Map<String, Object>map);
public List<CityInfo>singleCityExport(@Param("city")String city);
}
This annotation is related to spring-mybatis.xml Configured in targetDataSources Medium entry key value It matters .
I don't particularly understand many specific configurations here , But this configuration can be used . You can try .
边栏推荐
- Shanghai Yuge ASR CAT1 4G module 2-way low power 4G application
- Mysql-17- create and manage tables
- 5G网络整体架构
- 5g network overall architecture
- YYGH-7-用户管理
- Important basis for ERP software company selection
- Official answers to the "network security" competition questions of the 2022 national vocational college skills competition
- CSI以及本地盘的相关实现记录
- 自定义 cube-ui 弹出框dialog支持多个且多种类型的input框
- Difficulty calculation of Ethereum classic
猜你喜欢
随机推荐
全球国家(和地区)信息JSON数据
Pre training model parameter mismatch
numpy. reshape, numpy. Understanding of transfer
2022年全国职业院校技能大赛“网络安全”竞赛试题官方答案
Data warehouse: detailed explanation of hierarchical design
Enum
easyui下拉框选中触发事件
MR-WordCount
What is webrtc?
ES9023音频解码芯片的工作原理
idea创建类时自动添加注释
Capacity scheduling absolute value configuration queue usage and pit avoidance
Codeworks 5 questions per day (1700 for each)
YYGH-6-微信登录
5GgNB和ng-eNB的主要功能
数据中台:数据治理的七把利剑
[untitled]
What are the advantages of e-mail marketing? Why do sellers of shopline independent station attach so much importance to it?
Valueerror: iterative over raw text documents expected, string object received
Data middle office: construction ideas and implementation experience of data governance


![Video tutorial on website operation to achieve SEO operation [21 lectures]](/img/1f/9ae2ed5bfec5749c764630d1daccea.jpg)





![Taobao seo training video course [22 lectures]](/img/81/21e844542b35010760d061abe905e9.jpg)
