<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Spring 3.2.5 `AbstractRoutingDataSource`示例 > 原文: [https://howtodoinjava.com/spring-orm/spring-3-2-5-abstractroutingdatasource-example/](https://howtodoinjava.com/spring-orm/spring-3-2-5-abstractroutingdatasource-example/) [`AbstractRoutingDataSource`](https://docs.spring.io/spring/docs/3.2.5.RELEASE/javadoc-api/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.html)是 [**Spring 框架**](https://howtodoinjava.com)中非常有用的功能,如果您確實設計**允許基于某些條件的多個數據庫, 可能會針對每個用戶請求**更改。 一個例子可以是數據庫的使用。 當用戶屬于某個語言環境時,可以使用特定的數據庫;如果用戶屬于另一個語言環境,則可以切換到另一個語言環境。 根據定義,`AbstractRoutingDataSource`是一種抽象數據源實現,它基于查找鍵將`getConnection()`調用路由到各種目標`DataSource`之一。 后者通常(但不是必須)通過某些線程綁定的事務上下文來確定。 在這篇文章中,我將提供此功能的示例。 我正在為**使用路由數據源,根據用戶的語言環境**為用戶選擇適當的數據源。 在此示例中,我僅配置了兩個語言環境“`en`”和“`es`”。 您可以配置任意多個。 此外,語言環境不僅是更改數據源的唯一標準。 如果您有其他要求,請隨時添加自己的邏輯。 還請注意,我使用的是開發的源代碼,例如[在 Hibernate 4 和 Spring 3.2.5 之間集成](https://howtodoinjava.com/spring/spring-orm/spring-3-2-5-release-and-hibernate-4-integration-example-tutorial/)。 [下載源碼](https://drive.google.com/file/d/0B7yo2HclmjI4cVhBdElUTXBIYjA/edit?usp=sharing) ## **生成示例應用程序** **步驟 1)擴展`AbstractRoutingDataSource`類** 這是必需的,因為在這里您將決定要使用的數據源。 ```java package com.howtodoinjava.controller; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class MyRoutingDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { String language = LocaleContextHolder.getLocale().getLanguage(); System.out.println("Language obtained: "+ language); return language; } } ``` **步驟 2)在`jdbc.properties`中配置兩個數據源** 這不是必需的,在您的實現中可能不是必需的。 ```java jdbc.databaseurlOne=jdbc:mysql://127.0.0.1:3306/test jdbc.databaseurlTwo=jdbc:mysql://127.0.0.1:3306/testTwo ``` **步驟 3)在 spring 配置文件中配置多種類型的數據源** 首先配置各種數據源,而不必擔心如何訪問它們。 ```java <bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <bean id="concreteDataSourceOne" parent="abstractDataSource" p:url="${jdbc.databaseurlOne}"/> <bean id="concreteDataSourceTwo" parent="abstractDataSource" p:url="${jdbc.databaseurlTwo}"/> ``` **步驟 4)設置數據源的路由** 在這里,您實際上將在上述步驟中為所有配置的數據源定義鍵值對`targetDataSources`。 該值將是數據源 bean 名稱,而鍵將是來自`MyRoutingDataSource`中的`defineCurrentLookupKey()`方法的結果。 如果對于任何用戶請求都找不到任何內容,那么您還可以提及默認數據源。 如果將是默認值,并防止出現異常。 ```java <bean id="dataSource" class="com.howtodoinjava.controller.MyRoutingDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="en" value-ref="concreteDataSourceOne"/> <entry key="es" value-ref="concreteDataSourceTwo"/> </map> </property> <!-- <property name="defaultTargetDataSource" ref="concreteDataSourceOne"/> --> </bean> ``` **步驟 5)現在使用數據源** 這簡單。 對? ```java <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- HERE --> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${jdbc.dialect}</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> ``` 完成所有更改后,您的 spring 配置將如下所示: ```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:context="http://www.springframework.org/schema/context" 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:p="http://www.springframework.org/schema/p" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <context:annotation-config /> <context:component-scan base-package="com.howtodoinjava.controller" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" /> <!-- Step 3 --> <bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <bean id="concreteDataSourceOne" parent="abstractDataSource" p:url="${jdbc.databaseurlOne}"/> <bean id="concreteDataSourceTwo" parent="abstractDataSource" p:url="${jdbc.databaseurlTwo}"/> <!-- Step 4 --> <bean id="dataSource" class="com.howtodoinjava.controller.MyRoutingDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="en" value-ref="concreteDataSourceOne"/> <entry key="es" value-ref="concreteDataSourceTwo"/> </map> </property> <!-- <property name="defaultTargetDataSource" ref="concreteDataSourceOne"/> --> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basenames="messages" /> <!-- Declare the Interceptor --> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="locale" /> </mvc:interceptors> <!-- Declare the Resolver --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${jdbc.dialect}</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean> <bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> ``` ## **測試應用程序** 在測試應用程序之前,我已經在其中創建了兩個數據庫模式和兩個相似的表。 除了其中的數據外,這兩個表完全相同。 我有意讓它保持不變,以證明兩個不同的請求實際上正在訪問不同的數據庫。 ```java delimiter $$ CREATE DATABASE 'test' /*!40100 DEFAULT CHARACTER SET latin1 */$$ USE test$$ CREATE TABLE 'employee' ( 'ID' int(11) NOT NULL AUTO_INCREMENT, 'FIRSTNAME' varchar(30) DEFAULT NULL, 'LASTNAME' varchar(30) DEFAULT NULL, 'TELEPHONE' varchar(15) DEFAULT NULL, 'EMAIL' varchar(30) DEFAULT NULL, 'CREATED' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY ('ID') ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1$$ INSERT INTO 'test'.'employee' ('ID','FIRSTNAME','LASTNAME','TELEPHONE','EMAIL','CREATED') VALUES (4,'Lokesh','Gupta','9811111111','howtodoinjava@gmail.com',CURRENT_TIMESTAMP); CREATE DATABASE 'testtwo' /*!40100 DEFAULT CHARACTER SET latin1 */$$ USE testtwo$$ CREATE TABLE 'employee' ( 'ID' int(11) NOT NULL AUTO_INCREMENT, 'FIRSTNAME' varchar(30) DEFAULT NULL, 'LASTNAME' varchar(30) DEFAULT NULL, 'TELEPHONE' varchar(15) DEFAULT NULL, 'EMAIL' varchar(30) DEFAULT NULL, 'CREATED' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY ('ID') ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1$$ INSERT INTO 'testtwo'.'employee' ('ID','FIRSTNAME','LASTNAME','TELEPHONE','EMAIL','CREATED') VALUES (1,'Rakesh','Shukla','1234','email',CURRENT_TIMESTAMP); ``` **1)點擊網址:`http://localhost:8080/Spring3.2.5Hibernate4.0.1Integration/?locale=zh-CN`** ![AbstractRoutingDataSource_example_locale_en](https://img.kancloud.cn/52/46/5246a35c933a011bb457a978c7d7cd65_438x359.jpg) **2)點擊網址:`http://localhost:8080/Spring3.2.5Hibernate4.0.1Integration/?locale=es`** ![AbstractRoutingDataSource_example_locale_es](https://img.kancloud.cn/ae/c6/aec6d418b497f15c17b974a004e79d32_438x349.jpg) **3)點擊網址:`http://localhost:8080/Spring3.2.5Hibernate4.0.1Integration/?locale=fr`** 這將導致異常,因為我們既沒有為此語言環境設置任何數據源,也沒有任何默認數據源。 ```java HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.IllegalStateException: Cannot determine target DataSource for lookup key [fr] type Exception report message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.IllegalStateException: Cannot determine target DataSource for lookup key [fr] ``` [下載源碼](https://drive.google.com/file/d/0B7yo2HclmjI4cVhBdElUTXBIYjA/edit?usp=sharing) 如果需要更多說明,請給我評論。 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看