多くの場合、プロジェクトの複数のデータソース、特にデータの同期やタイミングタスクなどのプロジェクトに問題が発生します。複数のデータソースで最も厄介なことは、複数のデータソースを構成することではなく、柔軟で動的な方法でデータソースを切り替える方法です。たとえば、Spring and Hibernate Frameworkプロジェクトでは、Spring構成のDataSourceを構成してデータベースに接続し、SessionFactoryにバインドしてから、DAOレイヤーコードでSessionFactoryを指定してデータベース操作を実行します。
上の図に示すように、各ブロックはバインドされるようにバインドされています。複数のデータソースの場合、下の図と同じであると同じです。
2つのSessionFactoryがDAOレイヤーコードに記述されていることがわかります。このようにして、将来別のデータソースがある場合、コードを変更してSessionFactoryを追加する必要があります。明らかに、これは開閉の原則に準拠していません。
それからそれを行う正しい方法はあるはずです
コードは次のとおりです。
1。ApplicationContext.xml
<?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 = " 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 = " xmlns:task = "http://www.springframework.org/schema/task" xmlns:tx = "http://www.springframework.org/schema/TX" xmlns:util = " xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/a 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/spring-context-3.1.xsd 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 http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/jms http://www.springframework/ http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/Schema/ 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/oxm/spring-oxm-3.1.xsd http://www.springframework http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/TX http://www.springframework/schema/spring-tx-3.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd "> <context:annotation-config/> <context:component-scanベースパッケージ= < name = "locations"> <list> <value> classpath:com/resource/config.properties </value> </list> </property> </bean> <bean id = "datasourceone" destroy-method = "close"> <property name = "driverclass" value = "$ {dbone.jdbc.driverclass} value = "$ {dbone.jdbc.url}" /> <property name = "user" value = "$ {dbone.jdbc.user}" /> <プロパティ名= "パスワード" value = "$ {dbone.jdbc.password}" />> <プロパティname />> <Property name = "Minpoolsize" value = "$ {dbone.jdbc.minpoolsize}" /> <プロパティname = "maxpoolsize" value = "$ {dbone.jdbc.maxpoolsize}" /> < /bean> <bean id = " value = "$ {dbtwo.jdbc.driverclass}" /> <property name = "jdbcurl" value = "$ {dbtwo.url}" /> <プロパティ名= "user" value = "$ {dbtwo.jdbc.user}" value = "$ {dbtwo.jdbc.password}" /> <プロパティ名= "initialpoolsize" value = "$ {dbtwo.jdbc.initialpoolsize}" /> <プロパティ= "minpoolsize" value = "$ {dbtwo.jdbc.minpoolsize}" /< value = "$ {dbtwo.jdbc.maxpoolsize}"/> </bean> <bean id = "dynamicdatasource"> <プロパティ名= "ターゲットダタソース"> <マップキータイプ= " VALUE-REF = "DATASOURCETWO" KEY = "DATASOURCETWO"> </entr> </map> </property name = "defaulttargetdatasource" ref = "dataSourceone"> </bean> <bean id = "sessionfactory"> <property "datasource" ref = "dynamicdatasource"/> < name = "hibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <prop key = "hibernate.current_session_context_class"> org.springsionsionscontextextextextextextextexex key = "hibernate.show_sql"> false </prop> <prop key = "hibernate.format_sql"> true </prop> <prop key = "hbm2ddl.auto"> create </prop> </props> </property> <property name = "packageStoscan"> </propertion> </</</>> ID = "TransactionManager"> <Property name = "SessionFactory" Ref = "SessionFactory" /> < /bean> <aop:config> <aop:aop:aop:aop: "transactionpointcut" expression = "execution(*com.dao ..*(.. < /aop:config> <tx:アドバイスid = "txadvice" transaction-manager = "transactionmanager"> <tx:astributes> <tx:method name = "add*" propagation = "required" /> <tx:method name = "save*" propagation = "" reby " /> <tx:method =" "propagation =" mether propagation = "必須" /> <tx:method name = "*" read-only = "true" /> < /tx:属性> < /tx:アドバイス> <aop:config> <aop:aspect id = "datasourceaspect" ref = "dataSourceIntercept"> <aop:aop:pointcut id = "daOone" <aop:pointcut id = "daotwo" expression = "execution(*com.dao.two。*(..)" /> <aop:pointcut-ref = "daoo" method = "setdatasourceone" /> <aop:pointcut-ref = "daotwo" method = "setdatasourcetwo" /apsed </aop:config> </beans> 2。DynamicDataSource.Class
パッケージcom.core; Import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;パブリッククラスのdynamicdatasourceは、abstractroutingdatasourceを拡張します{@Overrideプロテクションオブジェクトsecurrentlookupkey(){return databasecontextholder.getCustomertype(); }} 3。DatabaseContextholder.class
パッケージcom.core; public class databasecontextholder {private static final threadlocal <string> contextholder = new threadlocal <string>(); public static void setCustomertype(String CustomerType){contextholder.set(customertype); } public static string getCustomertype(){return contextholder.get(); } public static void clearcustomertype(){contextholder.remove(); }} 4。DataSourceInterceptor.class
パッケージcom.core; org.aspectj.lang.joinpointをインポートします。 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エンティティクラス
パッケージcom.po; javax.persistence.columnをインポートします。 javax.persistence.entityをインポートします。 javax.persistence.idをインポートします。 javax.persistence.tableをインポートします。 @entity @table(name = "btsf_brand"、schema = "hotel")public class brand {private string id;プライベート文字列名;プライベート文字列URL; @id @column(name = "id"、unique = true、nullable = false、length = 10)public string getid(){return this.id; } public void setid(string id){this.id = id; } @column(name = "names"、nullable = false、length = 50)public string getnames(){return this.names; } public void setNames(string names){this.names = names; } @column(name = "url"、length = 200)public string geturl(){return this.url; } public void seturl(string url){this.url = url; }}パッケージcom.po; javax.persistence.columnをインポートします。 javax.persistence.entityをインポートします。 javax.persistence.idをインポートします。 javax.persistence.tableをインポートします。 @entity @table(name = "city"、schema = "car")public class city {private integer id;プライベート文字列名; @id @column(name = "id"、unique = true、nullable = false)public integer getid(){return id; } public void setid(integer id){this.id = id; } @column(name = "names"、nullable = false、length = 50)public string getname(){return name; } public void setName(string name){this.name = name; }} 6。BrandDaoImpl.Class
パッケージcom.dao.one; java.util.listをインポートします。 javax.annotation.resourceをインポートします。 Import org.hibernate.query; Import org.hibernate.sessionFactory; Import org.springframework.stereotype.repository; com.po.brandをインポートします。 @Repository Public Class BrandDaoImpl Irments Ibranddao {@Resource Protected SessionFactoryFactory; @suppresswarnings( "unchecked")@override public list <brand> findall(){string hql = "from brand";クエリquery = sessionfactory.getCurrentsession()。createQuery(hql); return query.list(); }} 7。CityDaoimpl.Class
パッケージcom.dao.two; java.util.listをインポートします。 javax.annotation.resourceをインポートします。 Import org.hibernate.query; Import org.hibernate.sessionFactory; Import org.springframework.stereotype.repository; com.po.cityをインポートします。 @Repository Public Class CityDaoimpl ImpityDao {@Resource Private SessionFactory Factory; @suppresswarnings( "unchecked")@override public list <city> find(){string hql = "from City";クエリquery = sessionfactory.getCurrentsession()。createQuery(hql); return query.list(); }} 8。Daotest.class
パッケージcom.test; java.util.listをインポートします。 javax.annotation.resourceをインポートします。 Import org.junit.test; Import org.junit.runner.runwith; org.springframework.test.context.contextconfigurationをインポートします。 Import org.springframework.test.context.junit4.springjunit4classrunner; org.springframework.test.context.transaction.transactionconfigurationをインポートします。 com.dao.one.ibranddaoをインポートします。 com.dao.two.icitydaoをインポートします。 com.po.brandをインポートします。 com.po.cityをインポートします。 @runwith(springjunit4classrunner.class)@contextconfiguration(locations = "classpath:com/resource/applicationcontext.xml")@transactionconfiguration(transactionManager = "transactionManager"、defaultrollollback = fals)公衆クラスdaotest {@Resource prive ibranddao branddao; @Resource Private IcityDao CityDao; @test public void testlist(){list <brand> brands = branddao.findall(); System.out.println(brands.size());リスト<city> cities = citydao.find(); System.out.println(cities.size()); }} AOPを使用して、データソースを動的に変更する目的を達成します。データソースを追加する必要がある場合、ApplicationContext構成ファイルにAOP構成を追加して、新しいDataSourceInterceptorを作成するだけです。コードを変更せずに。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。