当前位置:网站首页>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 .
边栏推荐
- 5G网络整体架构
- Flink 窗口机制 (两次等待, 最后兜底)
- 高质量国产立体声编解码器CJC8988,Pin to Pin替代WM8988
- The windows environment redis uses AOF persistence and cannot generate an AOF file. After generation, the content of the AOF file cannot be loaded
- Error: the following arguments are required:
- socke.io長連接實現推送、版本控制、實時活躍用戶量統計
- lombok @EqualsAndHashCode 注解如何让对象.equals()方法只比较部分属性
- Using pytorch and tensorflow to calculate the confusion matrix of classification model
- windows上安装redis并永久修改密码,及ssm框架集成redis
- MR-WordCount
猜你喜欢

Working principle of es9023 audio decoding chip

Lenovo hybrid cloud Lenovo xcloud, new enterprise IT service portal
![Taobao seo training video course [22 lectures]](/img/81/21e844542b35010760d061abe905e9.jpg)
Taobao seo training video course [22 lectures]

Difficulty calculation of Ethereum classic

若依实现下拉框

How to add live chat in your Shopify store?

JSP

YYGH-BUG-03

Xcode13.3.1 error reported after pod install

Oracle fundamentals summary
随机推荐
socke. IO long connection enables push, version control, and real-time active user statistics
RL practice (0) - and the platform xinchou winter season [rule based policy]
Xcode13.3.1 error reported after pod install
@Autowired注解为空的原因
重载,重写的区别,抽象类,接口的区别
深度學習19種損失函數
V4L2 驱动层分析
Main functions of 5ggnb and ng ENB
Independent station sellers are using the five e-mail marketing skills, do you know?
windows上安装redis并永久修改密码,及ssm框架集成redis
Jenkins continues integration 2
Yygh-6-wechat login
1404. 将二进制表示减到1的步骤数
简单手写debounce函数
[C language practice - printing hollow square and its deformation]
PS effect understanding record 2 color_ dodge color_ burn
Data center: Seven Swords of data governance
What is the e-commerce conversion rate so abstract?
联想混合云Lenovo xCloud,新企业IT服务门户
Qtcanpool knowledge 07:ribbon