当前位置:网站首页>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 .
边栏推荐
- Maskrcnn,fast rcnn, faster rcnn优秀视频
- Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
- Official answers to the "network security" competition questions of the 2022 national vocational college skills competition
- Filecoin hacker song developer competition
- The length of pytorch dataloader the difference between epoch and iteration
- Sharing tips for efficient scripting
- Oracle fundamentals summary
- Data middle office: six questions data middle office
- 什么是WebRTC?
- YYGH-BUG-03
猜你喜欢

JQ picture amplifier

qtcanpool 知 07:Ribbon

若依实现下拉框

File foundation - read / write, storage

Small ball playing

6. 毕业设计温湿度监控系统(ESP8266 + DHT11 +OLED 实时上传温湿度数据给公网服务器并在OLED显示屏上显示实时温湿度)

Oracle condition, circular statement

socke. IO long connection enables push, version control, and real-time active user statistics

mac下安装多个版本php并且进行管理

Difficulty calculation of Ethereum classic
随机推荐
Data middle office: an article that takes you to understand data middle office in simple terms
YYGH-BUG-03
Data warehouse: financial / banking theme layer division scheme
[untitled]
How to add live chat in your Shopify store?
Example of MVVM framework based on kotlin+jetpack
The windows environment redis uses AOF persistence and cannot generate an AOF file. After generation, the content of the AOF file cannot be loaded
Flink window mechanism (two waits and the last explanation)
windows上安装redis并永久修改密码,及ssm框架集成redis
Flink 窗口机制 (两次等待, 最后兜底)
重载,重写的区别,抽象类,接口的区别
mysql常用函数
什么是WebRTC?
Codeworks 5 questions per day (1700 for each)
Official answers to the "network security" competition questions of the 2022 national vocational college skills competition
idea创建类时自动添加注释
pkg打包node工程(express)
Pre training model parameter mismatch
Small ball playing
Deep learning 19 loss functions