1. 程式人生 > >spring-framework-4.1.6 mvc整合commons-dbutils-1.6註解式事務

spring-framework-4.1.6 mvc整合commons-dbutils-1.6註解式事務

dbutils 是 Apache 提供的一個開源 JDBC 工具類庫,對 JDBC 做了一些簡單的封裝,使用非常方便。在專案中經常會有用到事務,我們就來看看spring mvc是怎麼結合dbutils開發註解式事務的。 1、下載commons-dbutils-1.6.jar包,加入到專案中,然後在spring-mvc.xml全域性檔案編寫相關配置,如下:    <!-- c3p0 有連線池作用,使用properties檔案下的屬性值 --> <bean id ="dataSourceTarget" class= "com.mchange.v2.c3p0.ComboPooledDataSource"
 destroy-method="close" >          // 省略配置 </bean > <!-- 對資料來源進行代理 --> <bean id ="proxyDataSource" class= "org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy" > <constructor-arg > <ref bean ="dataSourceTarget" /> </constructor-arg > </bean > <
bean id ="transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name ="dataSource" ref="proxyDataSource" /> </bean > <tx:annotation-driven transaction-manager ="transactionManager" /> <!-- 直接使用資料來源的代理物件 --> <bean id ="queryRunner"
 class= "org.apache.commons.dbutils.QueryRunner" > <constructor-arg > <ref bean ="proxyDataSource" /> </constructor-arg > </bean > 2、建立Dao層和Service層 @Repository(value = "iTestDao" ) public class TestDao implements ITestDao { @Resource public QueryRunner queryRunner; @Override public int insertO2oTest(O2oTest o2oTest) throws SQLException {             // 做資料庫持久化操作 return null;       } } @Service(value = "iTestService" ) public class TestService implements ITestService { @Resource private ITestDao iTestDao; @Transactional(rollbackFor = Exception. class) @Override public String saveO2oTest( O2oTest o2oTest) throws SQLException {             // 做邏輯業務操作 return null;       } } 3、通過spring-mvc.xml配置queryRunner,就可以在DAO層使用dbutils操作資料庫,在Service層中通過在方法上使用標籤Transactional註解配置,就可以實現事務控制