Wir stoßen häufig Probleme mit mehreren Datenquellen in Projekten, insbesondere in Projekten wie Datensynchronisation oder Zeitaufgaben. Das schwierigste an mehreren Datenquellen ist nicht, mehrere Datenquellen zu konfigurieren, sondern wie die Datenquellen auf flexible und dynamische Weise wechseln. Beispielsweise konfigurieren wir in einem Frühlings- und Hibernate -Framework -Projekt häufig eine DataSource in der Federkonfiguration so, dass sie eine Verbindung zur Datenbank herstellen, und binden sie dann an die SessionFactory und geben dann den SessionFactory im DAO -Layer -Code an, um Datenbankoperationen durchzuführen.
Wie in der obigen Abbildung gezeigt, muss jeder Block gebunden sein. Wenn es sich um mehrere Datenquellen handelt, kann dies nur in der folgenden Abbildung gleich sein.
Es ist ersichtlich, dass zwei SessionFactory im DAO -Layer -Code geschrieben wurden. Wenn es in Zukunft eine andere Datenquelle gibt, müssen Sie den Code ändern und eine Sitzung hinzufügen. Offensichtlich entspricht dies nicht dem Prinzip des Öffnens und Schließens.
Dann sollte die richtige Art und Weise sein
Der Code ist wie folgt:
1. ApplicationContext.xml
<? xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: cache = "http://www.spingframework.org/schema/cache" xmlns: context = "http://wwwwwwwwwwwwwwwwwww. xmlns: jdbc = "http://www.springframework.org/schema/jdbc" Xmlns: Jee = "http://www.springframework.org/schema/jee xmlns: Lang = "http://www.springframework.org/schema/lang" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: oxm = "http://wwwwwwwwwwwww. xmlns: p = "http://www.springframework.org/schema/p" xmlns: task = "http://www.springframework.org/schema/task" xmlns: tx = "http://wwwww.spingframeWramework xmlns: util = "http://www.springframework.org/schema/util" xsi: Schemalocation = "http://www.springframework.org/schema/beans http://www.springramed.org/schema/schems/ 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 http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/context/context/context/context/context/skontex-context- http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springFramework.org/schema/jdbc http:/www.pringframe.org/jdbc/jdbc- http://www.springframework.org/schema/jee 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.springframe.org/schema/jms/jms/jms/jms/jms/jms/jms/jms/jms/jms/spring-jms-3ms-3.1.sd 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.springframe.org/sc. http://www.springframework.org/schema/oxm/spring-3.1.xsd http://www.springFramework.org/schema/task http://www.springframe.org/schema/task/task/sing- 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> <Eigenschaften name =" liste <wert> classPath: com/ressourcen/config.Properties </value> </list> </property> </bean> <bean id = "dataSourceone" Destroy-method = "close"> <property name = "driverClass" value = "$ {dbone.jdbc.driverClass}"/> <Eigenschaft = "JDBCUR" "JDBCUR". 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}" /> <Eigenschaft name = "minpoolsize" value = "$ {dbone.jdbc.minpoolsize}" /> <Eigenschaft name = "maxpoolsize" value = "$ {dbone.jdbc.maxpoolSize}" /> < /bean> <bean id = "dataSourcetwo" destroy-method "" cly "> < value = "$ {dbtwo.jdbc.driverClass}" /> <Eigenschaft name = "jdbcurl" value = "$ {dbtwo.jdbc.url}" /> <Eigenschaft name = "user" value = "$ {dBtwo.jdbc.user}}}}}}}}}}}" 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"> <Eigenschaft name = "targetDataSources"> <MAP Key-type = "java.lang.String"> <Eintrag Value-ref = "dataSourceone" key = "dataSourceone"> </> <eintrags-value-ref = "DataSourceOne"/dataSourcetWO "-" dataSourcetWO "-" dataSourcetWo "-" dataSourcetWo "-" dataSourcetwo ". </property> <property name="defaultTargetDataSource" ref="dataSourceOne"> </property> </bean> <bean id="sessionFactory"> <property name="dataSource" ref="dynamicDataSource" /> <property name="hibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect key = "hibernate.format_sql"> true </prop> <prop key = "hbm2ddl.auto"> create </prop> </props> </property> <Eigenschaft name = "packagestoscan"> <list> <value> com.po </value> </liste> </property> </probanfa. ref = "sessionFactory" /> < /bean> <AOP: config> <AOP: pointcut id = "transactionPointCut" Expression = "Ausführung (*com.dao ..*.*(..))" /> <aop: advisor rating-ref = "txadvice" pointcut-ref = "transactionpointcut" /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> < /> Transaction-Manager = "TransactionManager"> <tx: Attribute> <tx: Methode name = "add*" Propagation = "Erforderlich" /> <tx: method name = "speichern*" Propagation = "Erforderlich" /> <tx: method name = "update*" propagation = "erfordert" /> <tx: method name = "" recagation = "propagation =" provagation /> < /tx: Attribute> < /tx: Ratschläge> <AOP: config> <AOP: Aspekt id = "dataSourceEtPect" ref = "dataSourceIntercept"> <aop: pointcut id = "Daoone" Expression = "Ausführung (*com.dao.one. com.dao.two.*.*(..)) " /> <aop: vor pointcut-ref =" daoone "methode =" setDataSourceone " /> <aop: vor pointcut-ref =" daotwo "methode =" setDataSourcetwo " /> < /aoP: Aspekt: Aspekt: 2. DynamicDataSource.class
Paket com.core; import org.springframework.jdbc.datasource.lookup.abstractingDataSource; public class dynamicDataSource erweitert AbstractroutingDataSource {@Override Protected Object DeterminecurrentLookupkey () {return DatabaseContextHolder.getCustomerType (); }} A. DataBaseContexTHolder.Class
Paket com.core; public class DatabaseContextHolder {private statische endgültige ThreadLocal <String> condextHolder = new ThreadLocal <string> (); public static void setCustomerType (String customerType) {contextHolder.set (CustomerType); } public static String getCustomerType () {return contexHolder.get (); } public static void clearCustomerType () {contextHolder.remove (); }} 4.. DataSourceInterceptor.class
Paket com.core; import org.aspespectj.lang.joinpoint; import org.springframework.stereotype.comPonent; @Component public class DataSourceInterceptor {public void setDataSourceOne (joinpoint jp) {DatabaseContextHolder.setCustomerType ("DataSourceOne"); } public void setDataSourcetwo (joinpoint jp) {DataBaseContextHolder.setCustomerType ("DataSourcetwo"); }} 5. PO Entity Klasse
Paket com.po; import Javax.Persistence.Column; import Javax.Persistence.Entity; import Javax.Persistence.id; import Javax.Persistence.table; @Entity @table (name = "btsf_brand", schema = "Hotel") öffentliche Klasse Marke {private String -ID; private Zeichenfolgennamen; private String -URL; @Id @column (name = "id", eindeutig = true, nullable = false, length = 10) public String getId () {return this.id; } public void setID (String -ID) {this.id = id; } @Column (name = "namens", nullable = false, Länge = 50) public String getNames () {return this.names; } public void setNames (String -Namen) {this.names = names; } @Column (name = "url", Länge = 200) public String geturl () {return this.url; } public void seturl (String url) {this.url = url; }} Paket com.po; import Javax.Persistence.Column; import Javax.Persistence.Entity; import Javax.Persistence.id; import Javax.Persistence.table; @Entity @Table (name = "City", schema = "Car") öffentliche Klasse City {private Integer id; privater Zeichenfolge Name; @Id @column (name = "id", eindeutig = true, nullable = false) public Integer getId () {return id; } public void setId (Integer id) {this.id = id; } @Column (name = "namens", nullable = false, length = 50) public String getName () {return name; } public void setName (String -Name) {this.name = name; }} 6. BranddaoImpl.Class
Paket com.dao.one; importieren java.util.list; import Javax.annotation.Resource; import org.hibernate.query; import org.hiberNate.sessionFactory; import org.springframework.stereotype.repository; import com.po.brand; @Repository public class BrandDaoImpl implementiert Ibranddao {@resource Protected SessionFactory SessionFactory; @SuppressWarnings ("Deaktiviert") @Override public list <brand> findall () {String hql = "From Brand"; Query query = sessionfactory.getCurrentSession (). CreateEquery (HQL); return query.list (); }} 7. CityDaoImpl.Class
Paket com.dao.two; importieren java.util.list; import Javax.annotation.Resource; import org.hibernate.query; import org.hiberNate.sessionFactory; import org.springframework.stereotype.repository; com.po.city importieren; @Repository Public Class CityDaoImpl implementiert icityDao {@resource private sessionfactory SessionFactory; @SuppressWarnings ("Deaktiviert") @Override Public List <City> find () {String hql = "From City"; Query query = sessionfactory.getCurrentSession (). CreateEquery (HQL); return query.list (); }} 8. Daotest.Class
Paket com.test; importieren java.util.list; import Javax.annotation.Resource; import org.junit.test; import org.junit.runner.runwith; import org.springframework.test.context.contextConfiguration; import org.springframework.test.context.junit4.springjunit4ClasRunner; import org.springframework.test.context.transaction.transactionConfiguration; import com.dao.one.ibranddao; import com.dao.two.icitydao; import com.po.brand; com.po.city importieren; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml") @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) public class DaoTest { @Resource private IBrandDao brandDao; @Resource private icitydao Citydao; @Test public void testlist () {list <brand> brands = branddao.findall (); System.out.println (Brands.Size ()); Liste <City> cities = CityDao.find (); System.out.println (Cities.size ()); }} Verwenden Sie AOP, um den Zweck der dynamischen Änderung der Datenquelle zu erreichen. Wenn wir Datenquellen hinzufügen müssen, müssen wir nur eine AOP -Konfiguration in die Konfigurationsdatei applicationContext hinzufügen und einen neuen DataSourceInterceptor erstellen. Ohne Code zu ändern.
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.