Spring4 declarative transaction -- 01 annotation method, spring4 -- 01
1. Introduce the tx namespace in the spring configuration file
xmlns:tx="http://www.springframework.org/schema/tx"
2. Configure the Transaction Manager
<! -- Configure the Transaction Manager --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean>
3. Enable transaction Annotation
<! -- Enable transaction annotation --> <tx: annotation-driven transaction-manager = "transactionManager"/>
4. Add @ Transactional above the corresponding business code method to indicate that this method is managed by transactions.
// Spring declarative transactions@ Transactional@ Override public void purchase (String isbn, String userName) {// 1. find the price int price = bookShopDao according to the book number. findPriceByIsbn (isbn); // 2. inventory-1 bookShopDao. updateBookStock (isbn); // 3. account Balance-price bookShopDao. updateAccount (userName, price );}
Transaction attributes:
1. UsePropagationDeclare the transactionPropagation attributesBy default, that is, REQUIRED is included in the preceding transaction. Discard your own processing of the transaction REQUIRES_NEW. Start a new transaction (the external transaction is suspended before and after the method is executed). 2. UseIsolationSpecify the transaction'sIsolation level, The most common value is READ_COMMITTED read and submit
3. By default, Spring declarative transactions apply to allRuntimeSame LengthRollback. You can also specify the configuration for the corresponding property. Generally, you can use the default value. UseNoRollbackForAn exception that does not roll back. Others are similar.
4. UseReadOnlySpecify whether the transaction isRead-Only, Indicates that this transaction only reads data but does not update data, which can help the database engine optimize transactions. If it is really a method to read only the database, you should set readOnly = true
5. UseTimeoutSpecifies the transactions that can be occupied before force rollbackTime