Spring有兩種交易處理方式,編程式交易處理(programmatic transaction management)與聲明式交易處理(declarative transaction management)。
編程式交易處理比傳統的JDBC事務有所改進,但是還是要實現具體方法。雖然有三種實現Spring編程式交易處理的方法,但其中都必須寫入特定的代碼,這樣做一是代碼量增加,DAO裡面每個方法都加上那些必須要寫上的代碼那也是很煩人的,二是耦合度也提高了,哪天哪天不用Spring用XX也說不定呀....-_-!。
聲明式事務處事,在DAO中你的對資料庫操作的代碼可以隨意的寫上,不用加任何其它代碼,事務的處理交給Spring的TransactionProxyFactoryBean來代為處理。
xxDAO:
- .......
- //對資料庫的操作
- public void update(String name,String password){
- //業務處理方法
- //update1();
- //update2();
- }
- ......
Spring設定檔
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName">
- <value>com.microsoft.jdbc.sqlserver.SQLServerDrivervalue>
- property>
- <property name="url">
- <value>jdbc:microsoft:sqlserver://localhost:1433/xxvalue>
- property>
- <property name="name">
- <value>usenamevalue>
- property>
- <!-- 設定密碼 -->
- <property name="msg">
- <value>passwordvalue>
- property>
- bean>
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource">
- <ref bean="dataSource" />
- property>
- bean>
- <bean id="xxDAOProxy"
- class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
- <property name="transactionManager">
- <ref bean="transactionManager" />
- property>
- <property name="target">
- <ref bean="xxDAO" />
- property>
- <property name="transactionAttributes">
-