


Cet article vous présente principalement les informations pertinentes sur la façon dont Spring MVC configure deux sources de données pour implémenter un projet Java pour connecter deux bases de données en même temps. L'article le présente en détail à travers un exemple de code, ce qui est d'une grande aide pour tout le monde. Il a une certaine valeur de référence et d'apprentissage. Les amis qui en ont besoin peuvent y jeter un œil ci-dessous.
Avant-propos
Cet article présente principalement la méthode de configuration de sources de données doubles avec Spring MVC pour réaliser un projet Java connectant deux bases de données en même temps temps. Partager Sortez pour votre référence et votre étude. Jetons un coup d'œil à l'introduction détaillée :
Méthode de mise en œuvre :
La source de données se trouve dans Configuration dans le fichier de configuration
<pre name="code" class="java"><?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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com"></context:component-scan> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:com/resource/config.properties</value> </list> </property> </bean> <bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${dbOne.jdbc.driverClass}" /> <property name="jdbcUrl" value="${dbOne.jdbc.url}" /> <property name="user" value="${dbOne.jdbc.user}" /> <property name="password" value="${dbOne.jdbc.password}" /> <property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" /> </bean> <bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${dbTwo.jdbc.driverClass}" /> <property name="jdbcUrl" value="${dbTwo.jdbc.url}" /> <property name="user" value="${dbTwo.jdbc.user}" /> <property name="password" value="${dbTwo.jdbc.password}" /> <property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" /> </bean> <bean id="dynamicDataSource" class="com.core.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="dataSourceOne" key="dataSourceOne"></entry> <entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceOne"> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dynamicDataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hbm2ddl.auto">create</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.po</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:config> <aop:pointcut id="transactionPointCut" expression="execution(* com.dao..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor"> <aop:pointcut id="daoOne" expression="execution(* com.dao.one.*.*(..))" /> <aop:pointcut id="daoTwo" expression="execution(* com.dao.two.*.*(..))" /> <aop:before pointcut-ref="daoOne" method="setdataSourceOne" /> <aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" /> </aop:aspect> </aop:config> </beans>
DynamicDataSource.class
package com.core; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { return DatabaseContextHolder.getCustomerType(); } }
DatabaseContextHolder .class définit la classe de la source de données
package com.core; public class DatabaseContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); <span style="white-space:pre"> </span>//设置要使用的数据源 public static void setCustomerType(String customerType) { contextHolder.set(customerType); } <span style="white-space:pre"> </span>//获取数据源 public static String getCustomerType() { return contextHolder.get(); } <span style="white-space:pre"> </span>//清除数据源,使用默认的数据源 public static void clearCustomerType() { contextHolder.remove(); } }
DataSourceInterceptor.class
package com.core; import org.aspectj.lang.JoinPoint; import org.springframework.stereotype.Component; @Component public class DataSourceInterceptor { <span style="white-space:pre"> </span>//数据源1 public static final String SOURCE_PLAN = "<span style="font-family: Arial, Helvetica, sans-serif;">dataSourceOne</span><span style="font-family: Arial, Helvetica, sans-serif;">";</span> //数据源2 <pre name="code" class="java"><span style="white-space:pre"> </span>public static final String SOURCE_FUND = "<span style="font-family: Arial, Helvetica, sans-serif;">dataSourceTwo</span>"; }
source de données springMVC
jdbc_driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver <pre name="code" class="java">dataSourceOne<span style="font-family: Arial, Helvetica, sans-serif;">=jdbc:sqlserver://115.29.***.**;DatabaseName=DB_GuiHua</span>
jdbc_username=**jdbc_password=**
dataSourceTwo<span style="font-family: Arial, Helvetica, sans-serif;">=jdbc:sqlserver://115.29.***.*;DatabaseName=DB_Fund</span>
Spring MVC aura une source de données par défaut. vous devez changer la source de données, vous devez le faire avant d'appeler la transaction
DataSourceContextHolder.setDbType(DataSourceType.SOURCE_FUND);//更换数据源
/** * @ClassName: DataSourceContextHolder * @Description: 数据库切换工具类 * @author: wzx * @date: 2016-07-27 上午10:26:01 */ public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDbType(String dbType) { contextHolder.set(dbType); } public static String getDbType() { return ((String) contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); } }
Résumé
.Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

L'article discute de l'utilisation de Maven et Gradle pour la gestion de projet Java, la construction de l'automatisation et la résolution de dépendance, en comparant leurs approches et leurs stratégies d'optimisation.

L'article discute de la création et de l'utilisation de bibliothèques Java personnalisées (fichiers JAR) avec un versioning approprié et une gestion des dépendances, à l'aide d'outils comme Maven et Gradle.

L'article examine la mise en œuvre de la mise en cache à plusieurs niveaux en Java à l'aide de la caféine et du cache de goyave pour améliorer les performances de l'application. Il couvre les avantages de configuration, d'intégration et de performance, ainsi que la gestion de la politique de configuration et d'expulsion le meilleur PRA

L'article discute de l'utilisation de JPA pour la cartographie relationnelle des objets avec des fonctionnalités avancées comme la mise en cache et le chargement paresseux. Il couvre la configuration, la cartographie des entités et les meilleures pratiques pour optimiser les performances tout en mettant en évidence les pièges potentiels. [159 caractères]

Le chargement de classe de Java implique le chargement, la liaison et l'initialisation des classes à l'aide d'un système hiérarchique avec Bootstrap, Extension et Application Classloaders. Le modèle de délégation parent garantit que les classes de base sont chargées en premier, affectant la classe de classe personnalisée LOA


Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Version crackée d'EditPlus en chinois
Petite taille, coloration syntaxique, ne prend pas en charge la fonction d'invite de code

Version Mac de WebStorm
Outils de développement JavaScript utiles

Navigateur d'examen sécurisé
Safe Exam Browser est un environnement de navigation sécurisé permettant de passer des examens en ligne en toute sécurité. Ce logiciel transforme n'importe quel ordinateur en poste de travail sécurisé. Il contrôle l'accès à n'importe quel utilitaire et empêche les étudiants d'utiliser des ressources non autorisées.

SublimeText3 version anglaise
Recommandé : version Win, prend en charge les invites de code !

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP