spring(16)------spring的数据源配置
在spring中,通過XML的形式實現數據源的注入有三種形式。
一。使用spring自帶的DriverManagerDataSource
使用DriverManagerDataSource配置數據源與直接使用jdbc在效率上沒有多大的差別,使用DriverManagerDataSource配置數據源
的代碼實比例如以下,這里重點研究spring的數據源配置。就採用spring編程式事務處理來來研究數據源的配置。
所須要的jar包和spring編程式配置:http://blog.csdn.net/yhl_jxy/article/details/51167351
(1)HelloDAO類:
package com.lanhuigu.spring.dao;import javax.sql.DataSource;import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate;public class HelloDAO {private DataSource dataSource;private PlatformTransactionManager transactionManager;//通過set方式注入public void setDataSource(DataSource dataSource) {this.dataSource = dataSource;}public void setTransactionManager(PlatformTransactionManager transactionManager) {this.transactionManager = transactionManager;}//=============編程式事務處理的3種編寫形式====================//第一種編寫public int create(String msg) {System.out.println(msg+"開始!"); //使用TransactionTemplate進行事務處理編程 TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); //調用TransactionTemplate的execute方法 Object result = transactionTemplate.execute( new TransactionCallback() { //覆蓋TransactionCallback的doInTransaction()方法 @Override public Object doInTransaction(TransactionStatus status) { // TODO Auto-generated method stub //在該方法內對數據庫進行添加操作 System.out.println("加入對象進行"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); //第一次運行不打開,第二次運行打開 //jdbcTemplate.update("insert into t_user_main values(2,'test',24)"); jdbcTemplate.update("insert into t_user_main values(1,'test',24)"); System.out.println("加入對象結束"); return null; } } ); return 0; } //另外一種編寫 /*public int create(String msg) { System.out.println(msg+"開始!"); DefaultTransactionDefinition dtd = new DefaultTransactionDefinition(); TransactionStatus status = transactionManager.getTransaction(dtd); try { //使用JdbcTemplate與數據庫進行交互 System.out.println("加入對象進行"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update("insert into t_user_main values(1,'test',24)"); } catch (DataAccessException ex) { // TODO: handle exception transactionManager.rollback(status); throw ex; } finally { transactionManager.commit(status); } return 0; }*/ //第三種編寫 /*public int create(String msg) { System.out.println(msg+"開始。"); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // TODO Auto-generated method stub JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update("insert into t_user_main values(1,'test',24)"); } }); return 0; }*/ /*//============聲明式事務編程============ public int create(String msg) { System.out.println(msg+"開始"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); //新增數據 jdbcTemplate.update("insert into t_user_main values(1,'test',24)"); System.out.println(msg+"結束"); return 0; }*/ }
(2)使用spring自帶的DataSourceTransactionManager配置數據源: <?xml version="1.0" encoding="UTF-8"?><!--- Application context definition for JPetStore's business layer.- Contains bean references to the transaction manager and to the DAOs in- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").--> <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:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- spring編程式事務配置 --><!-- 1.配置數據源(dataSource) --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- oracle數據庫驅動 --><property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property><!-- 數據庫連接 --><property name="url"><value>jdbc:oracle:thin:@localhost:1521/XE</value></property><!-- 數據庫用戶名 --><property name="username"><value>system</value></property><!-- 數據庫密碼 --><property name="password"><value>123456</value></property></bean><!-- 2.設定transactionManager --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 這里配置的dataSource是DataSourceTransactionManager類中的屬性,在類中有著屬性的定義:private DataSource dataSource; 跟以下配置的HelloDAO中的dataSource不是用在一個地方。是一個東西用在兩個地方--><property name="dataSource"><ref bean="dataSource"/></property></bean><!-- 3.配置事務管理目標類 --><bean id="helloDAO" class="com.lanhuigu.spring.dao.HelloDAO"><!-- dataSource屬性 --><property name="dataSource"><ref bean="dataSource"/></property><!-- transactionManager屬性 --><property name="transactionManager"><ref bean="transactionManager"/></property> </bean></beans> (3)測試程序: package com.lanhuigu.spring.test;import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.lanhuigu.spring.dao.HelloDAO; import com.lanhuigu.spring.impl.IUser;public class TestJDBCTemplate {@Testpublic void testJDBCTemplate(){//1.創建spring容器ApplicationContext actx =new ClassPathXmlApplicationContext("/applicationContext.xml");//2.編程式測試HelloDAO helloDAO = (HelloDAO) actx.getBean("helloDAO");helloDAO.create("加入對象");} } (4)總結:之所以說使用這樣的方式跟jdbc直接操作數據庫效率上沒有多大差別,是由于DriverManagerDataSource建立連接是僅僅要有連接就新建一個connection,
根本沒有連接池的作用,這樣做的話,數據庫一直開連接,數據庫崩掉是早晚的事。
二。使用DBCP配置連接池
須要添加jar包例如以下:
在目錄spring-framework-2.5.6\lib\jakarta-commons下的commons-collections.jar,commons-dbcp.jar,commons-pool.jar。
改動上面使用上面DriverManagerDataSource配置數據源的配置文件,改動為DBCP配置數據源的方式,改動后的xml例如以下。其它不變:
<?xml version="1.0" encoding="UTF-8"?><!--- Application context definition for JPetStore's business layer.- Contains bean references to the transaction manager and to the DAOs in- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").--> <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:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- spring編程式事務配置 --><!-- 1.配置數據源(dataSource) --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><!-- oracle數據庫驅動 --><property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property><!-- 數據庫連接 --><property name="url"><value>jdbc:oracle:thin:@localhost:1521/XE</value></property><!-- 數據庫用戶名 --><property name="username"><value>system</value></property><!-- 數據庫密碼 --><property name="password"><value>123456</value></property><!-- 最大連接數據庫連接數,設置為0時。表示沒有限制 --><property name="maxActive"><value>255</value></property><!-- 最大等待連接中的數量,設置為0時,表示沒有限制 --><property name="maxIdle"><value>2</value></property><!-- 最大等待秒數,單位為毫秒。 超過時間會報出錯誤信息 --><property name="maxWait"><value>50000</value></property></bean><!-- 2.設定transactionManager --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 這里配置的dataSource是DataSourceTransactionManager類中的屬性。在類中有著屬性的定義:private DataSource dataSource; 跟以下配置的HelloDAO中的dataSource不是用在一個地方。是一個東西用在兩個地方--><property name="dataSource"><ref bean="dataSource"/></property></bean><!-- 3.配置事務管理目標類 --><bean id="helloDAO" class="com.lanhuigu.spring.dao.HelloDAO"><!-- dataSource屬性 --><property name="dataSource"><ref bean="dataSource"/></property><!-- transactionManager屬性 --><property name="transactionManager"><ref bean="transactionManager"/></property> </bean></beans> 注意:當你執行程序時,報錯的話,是HelloDAO中
jdbcTemplate.update("insert into t_user_main values(1,'test',24)");插入數據id反復導致的,
換個id或刪掉數據庫表的數據。然后再執行。
關于DBCP的總結:
1. 首先得了解配置文件里的屬性:
BasicDataSource提供close()方法關閉數據源。一定記得設置destroy-method=”close”。以便spring容器關閉時。
數據源可以得到正常的關閉。還有非常多經常使用的property屬性例如以下:
defaultAutoCommit:設置從數據源中返回的連接是否採用自己主動提交的機制,默覺得true;
defaultReadOnly:設置數據源是否僅能運行僅僅讀操作,默覺得false;
maxActive:最大連接數據庫連接數,設置為0時,表示沒有限制;
mmaxIdle:最大等待連接中的數量,設置為0時,表示沒有限制;
maxWait:最大等待秒數。單位為毫秒。超時報錯;
validationQuery:用于驗證連接是否成功的查詢SQL語句。SQL語句必須至少要返回一行數據;
removeAbandoned:是否自我中斷,默認是false;
removeAbandonedTimout:幾秒后數據庫連接會自己主動斷開,在removeAbandoned為true,提供該值;
logAbandoned:是否記錄中斷事件,默覺得false;
2.使用連接池
使用這樣的方式的優點在于數據庫連接時建立了連接池。連接池的優點就是當你建立連接時。從連接池中找。找到就使用已有連接,
找不到新建連接,類推到最大連接數時,假設沒有空暇可用連接,就等待。用完就釋放到連接池。做到資源使用最大化。不會
無限制的建立連接。把數據庫搞崩了。
三,使用C3P0連接數據源
須要增加c3p0的jar包,這里使用c3p0-0.9.1.2.jar,改動spring數據源配置文件。
<?xml version="1.0" encoding="UTF-8"?
> <!-- - Application context definition for JPetStore's business layer. - Contains bean references to the transaction manager and to the DAOs in - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation"). --> <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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- spring編程式事務配置 --> <!-- 1.配置數據源(dataSource) --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- oracle數據庫驅動 --> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <!-- 數據庫連接 --> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@localhost:1521/XE</value> </property> <!-- 數據庫username --> <property name="user"> <value>system</value> </property> <!-- 數據庫密碼 --> <property name="password"> <value>123456</value> </property> </bean> <!-- 2.設定transactionManager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 這里配置的dataSource是DataSourceTransactionManager類中的屬性, 在類中有著屬性的定義:private DataSource dataSource; 跟以下配置的HelloDAO中的dataSource不是用在一個地方,是一個東西用在兩個地方--> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <!-- 3.配置事務管理目標類 --> <bean id="helloDAO" class="com.lanhuigu.spring.dao.HelloDAO"> <!-- dataSource屬性 --> <property name="dataSource"> <ref bean="dataSource"/> </property> <!-- transactionManager屬性 --> <property name="transactionManager"> <ref bean="transactionManager"/> </property> </bean> </beans>
使用總結: ComboPooledDataSource和BasicDataSource一樣都提供一個當spring容器關閉時用于數據源正確關閉的close()方法。
C3P0擁有比DBCP更豐富的配置屬性,通過這些屬性,能夠對數據源進行各種有效的控制:?
acquireIncrement:當連接池中的連接用完時,C3P0一次性創建新連接的數目;?
acquireRetryAttempts:定義在從數據庫獲取新連接失敗后反復嘗試獲取的次數。默覺得30;
acquireRetryDelay:兩次連接中間隔時間,單位毫秒,默覺得1000;?
autoCommitOnClose:連接關閉時默認將全部未提交的操作回滾。默覺得false;?
automaticTestTable: C3P0將建一張名為Test的空表,并使用其自帶的查詢語句進行測試。
假設定義了這個參數,那么屬性preferredTestQuery將被忽略。
你不能在這張Test表上進行不論什么操作,它將中為C3P0測試所用,默覺得null;?
?breakAfterAcquireFailure:獲取連接失敗將會引起全部等待獲取連接的線程拋出異常。
可是數據源仍有效保留。
并在下次調?? 用getConnection()的時候繼續嘗試獲取連接。
假設設為true,那么在嘗試獲取連接失敗后該數據源將申明已斷開并永久關閉。默覺得 false;?
checkoutTimeout:當連接池用完時client調用getConnection()后等待獲取新連接的時間,超時后將拋出SQLException,
如設為0則無限期等待。單位毫秒,默覺得0;?
connectionTesterClassName: 通過實現ConnectionTester或QueryConnectionTester的類來測試連接,類名需設置為全限定名。
默覺得 com.mchange.v2.C3P0.impl.DefaultConnectionTester;?
idleConnectionTestPeriod:隔多少秒檢查全部連接池中的空暇連接,默覺得0表示不檢查;?
initialPoolSize:初始化時創建的連接數,應在minPoolSize與maxPoolSize之間取值。
默覺得3;?
maxIdleTime:最大空暇時間,超過空暇時間的連接將被丟棄。
為0或負數則永不丟棄。默覺得0。?
maxPoolSize:連接池中保留的最大連接數。
默覺得15;?
maxStatements:JDBC的標準參數。用以控制數據源內載入的PreparedStatement數量。
但因為預緩存的Statement屬 于單個Connection而不是整個連接池。
所以設置這個參數須要考慮到多方面的因素。
假設maxStatements與 maxStatementsPerConnection均為0,則緩存被關閉。默覺得0;?
maxStatementsPerConnection:連接池內單個連接所擁有的最大緩存Statement數。
默覺得0;?
numHelperThreads:C3P0是異步操作的。緩慢的JDBC操作通過幫助進程完畢。擴展這些操作能夠有效的提升性能,
通過多線程實現多個操作同一時候被運行。
默覺得3。?
preferredTestQuery:定義全部連接測試都運行的測試語句。
在使用連接測試的情況下這個參數能顯著提高測試速度。
測試的表必須在初始數據源的時候就存在。默覺得null。?propertyCycle: 用戶改動系統配置參數運行前最多等待的秒數。默覺得300。?
testConnectionOnCheckout:因性能消耗大請僅僅在須要的時候使用它。假設設為true那么在每一個connection提交的時候都 將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable?
等方法來提升連接測試的性能。默覺得false;?
testConnectionOnCheckin:假設設為true那么在取得連接的同一時候將校驗連接的有效性。
默覺得false。
這樣的方式須要在Tomcat中server.xml中配置數據源,也就是把上面的數據配置放在server.xml中,同一時候須要在spring配置文件里進行jndi配置。很麻煩。
一般不用。
轉載于:https://www.cnblogs.com/mthoutai/p/7230772.html
總結
以上是生活随笔為你收集整理的spring(16)------spring的数据源配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 9 揭秘(14. HTTP/2
- 下一篇: 扩号匹配问题