Spring framework study notes 7: Transaction Management and cases, spring Study Notes

Source: Internet
Author: User

Spring framework study notes 7: Transaction Management and cases, spring Study Notes

Spring provides a mechanism for managing transactions in projects.

I have written a simple introduction to the transaction essay: http://www.cnblogs.com/xuyiqing/p/8430214.html

There is another Hibernate Transaction Management: http://www.cnblogs.com/xuyiqing/p/8449167.html

Make a comparison.

 

Spring manages the unique attributes of transactions:

Transaction propagation behavior: propagation behavior refers to how the transaction method should be implemented when a transaction method is called by another transaction method.

For example, when the methodA transaction method calls the methodB transaction method, does methodB continue to run in the transaction of the caller methodA or start a new transaction for itself, this is determined by the transaction Propagation Behavior of methodB.

 

1. PROPAGATION_REQUIRED: If no transaction exists, a new transaction is created. If a transaction exists, it is added to the transaction,This is the most common setting..

2. PROPAGATION_SUPPORTS: supports the current transaction. If a transaction exists, it is added. If no transaction exists, it is executed as a non-transaction. '

3. PROPAGATION_MANDATORY: supports the current transaction. If the current transaction exists, it is added. If the current transaction does not exist, an exception is thrown.

4. PROPAGATION_REQUIRES_NEW: Creates a new transaction no matter whether there is a transaction in the current store.

5. PROPAGATION_NOT_SUPPORTED: executes the operation in non-transaction mode. If a transaction exists, the current transaction is suspended.

6. PROPAGATION_NEVER: runs in non-transaction mode. If a transaction exists, an exception is thrown.

7. PROPAGATION_NESTED: if a transaction exists, it is executed within the nested transaction. If no transaction exists, perform operations similar to PROPAGATION_REQUIRED.

 

 

The following shows the transaction case: simpleSimulated Transfer

Required packages:

Create a new table and put it into the data:

Package dao; public interface AccountDao {// Add void increaseMoney (Integer id, Double money); // subtract void decreaseMoney (Integer id, Double money );}
package dao;import org.springframework.jdbc.core.support.JdbcDaoSupport;public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao  {    @Override    public void increaseMoney(Integer id, Double money) {                getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id);            }    @Override    public void decreaseMoney(Integer id, Double money) {        getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);    }}
Package service; public interface AccountService {// transfer method void transfer (Integer from, Integer to, Double money );}
Package service; import dao. accountDao; public class AccountServiceImpl implements AccountService {private AccountDao ad; @ Override public void transfer (final Integer from, final Integer to, final Double money) {// deduct money ad. decreaseMoney (from, money); // Add ad. increaseMoney (to, money);} public void setAd (AccountDao ad) {this. ad = ad ;}}
package tx;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import service.AccountService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo {        @Resource(name="accountService")    private AccountService as;        @Test    public void fun1(){                as.transfer(1, 2, 100d);            }}

Configuration file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" 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 -4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <! -- Specify spring to read db. properties configuration --> <context: property-placeholder location = "classpath: db. properties"/> <! -- The core Transaction Manager encapsulates all transaction operations. dependent on the connection pool --> <bean name = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <! -- Configure transaction notification --> <tx: advice id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <! -- In the unit of method, specify the transaction attribute isolation applied by the method: isolation level propagation: propagation Behavior read-only: whether to read only other method configurations are not used, but they are usually unified configuration --> <tx: method name = "save *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method name = "persist *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method name = "update *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method Name = "modify *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method name = "delete *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method name = "remove *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> <tx: method name = "get *" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "true"/> <tx: method name = "find *" Isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "true"/> <tx: method name = "transfer" isolation = "REPEATABLE_READ" propagation = "REQUIRED" read-only = "false"/> </tx: attributes> </tx: advice> <! -- Configure woven --> <aop: config> <! -- Configure the cut-point expression --> <aop: pointcut expression = "execution (* service. * ServiceImpl. * (..)" id = "txPc"/> <! -- Configuration aspect: Notification + cut point advice-ref: Notification name pointcut-ref: Cut Point name --> <aop: advisor advice-ref = "txAdvice" pointcut-ref = "txPc"/> </aop: config> <! -- 1. bind the connection pool --> <bean name = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "> <property name =" jdbcUrl "value =" $ {jdbc. jdbcUrl} "> </property> <property name =" driverClass "value =" $ {jdbc. driverClass} "> </property> <property name =" user "value =" $ {jdbc. user} "> </property> <property name =" password "value =" $ {jdbc. password} "> </property> </bean> <! -- 2. dao --> <bean name = "accountDao" class = "dao. accountDaoImpl "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <! -- 3. service --> <bean name = "accountService" class = "service. accountServiceImpl "> <property name =" ad "ref =" accountDao "> </property> </bean> </beans>

Db. properties

jdbc.jdbcUrl=jdbc:mysql:///mybasejdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=xuyiqing

 

Result After running Demo:

 

Transfer successful!

 

Supplement:

You can use annotations to replace the XML configuration file:

The configuration file only needs one line:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" 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 -4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <! -- Specify spring to read db. properties configuration --> <context: property-placeholder location = "classpath: db. properties"/> <! -- The core Transaction Manager encapsulates all transaction operations. dependent on the connection pool --> <bean name = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <! -- Transaction template object --> <bean name = "transactionTemplate" class = "org. springframework. transaction. support. transactionTemplate "> <property name =" transactionManager "ref =" transactionManager "> </property> </bean> <! -- Enable the use of annotations to manage aop transactions --> <tx: annotation-driven/> <! -- 1. bind the connection pool --> <bean name = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "> <property name =" jdbcUrl "value =" $ {jdbc. jdbcUrl} "> </property> <property name =" driverClass "value =" $ {jdbc. driverClass} "> </property> <property name =" user "value =" $ {jdbc. user} "> </property> <property name =" password "value =" $ {jdbc. password} "> </property> </bean> <! -- 2. dao --> <bean name = "accountDao" class = "dao. accountDaoImpl "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <! -- 3. service --> <bean name = "accountService" class = "service. accountServiceImpl "> <property name =" ad "ref =" accountDao "> </property> </bean> </beans>
Package service; import org. springframework. transaction. annotation. isolation; import org. springframework. transaction. annotation. propagation; import org. springframework. transaction. annotation. transactional; import dao. accountDao; @ Transactional (isolation = Isolation. REPEATABLE_READ, propagation = Propagation. REQUIRED, readOnly = true) public class AccountServiceImpl implements AccountService {private AccountDao ad; @ Override @ Transactional (isolation = Isolation. REPEATABLE_READ, propagation = Propagation. REQUIRED, readOnly = false) public void transfer (final Integer from, final Integer to, final Double money) {// deduct money ad. decreaseMoney (from, money); // Add ad. increaseMoney (to, money);} public void setAd (AccountDao ad) {this. ad = ad ;}}

 

 

The test is successful again!

The Spring framework is now available.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.