Function 4-Spring transaction (JDBC) and Spring JDBC

Source: Internet
Author: User

Function 4-Spring transaction (JDBC) and Spring JDBC
Summary

There are three transaction implementation methods: JTA, Spring transaction, and Web Container. This article describes Spring transactions.

Spring transactions are divided into two core objects: Implementation of Spring transactions.

There are three methods to implement Spring transactions. Declarative, annotated, and code methods. The declaration method is widely used in actual projects. The annotation method requires @ Transactional annotation to be added to each method. The Code redundancy is relatively high. The code method is only for better understanding of the Spring transaction mechanism and is not applicable to actual projects.

Core object PlatformTransactionManager

Transaction Management Interface.

TransactionDefinition

The attribute or definition object of the transaction. The attributes are as follows:

Isolation: the Isolation level of transactions.

Propagation: the transaction Propagation mechanism.

Timeout: Timeout.

Read-only: whether the transaction is read-only.

TransactionStatus

Indicates a newly created transaction or an existing transaction.

The sample code is as follows:

1 // Step 1: Create the transaction property object TransactionDefinition, and create the transaction management object TransactionManager. 2 // create the transaction property object 3 DefaultTransactionDefinition def = new DefaultTransactionDefinition (); 4 def. setName ("trans1"); 5 def. setPropagationBehavior (TransactionDefinition. PROPAGATION_REQUIRED); 6 // create the transaction management object 7 cetcetransactionmanager transcationManager = new DataSourceTransactionManager (); 8 9 // Step 2: Get the transaction object, 10 TransactionStatus status = transcationManager. getTransaction (def); 11 // Step 3: implement the business logic code 12 try13 {14 // code logic 15} 16 catch (Exception e) 17 {18 transcationManager. rollback (status); 19 throw e; 20} 21 transcationManager. commit (status );
View Code

 

Implementation Method

There are three methods to implement spring transactions. Configure the aspect mode, annotation mode, and code mode. The configuration aspect method is widely used in actual projects. The annotation method requires @ Transactional annotation to be added to each method. The Code redundancy is high. The code method is only for better understanding of the Spring transaction mechanism and is not applicable to actual projects.

Configuration section

Step 1: Configure transaction management.

<! -- Configure Transaction Management --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean>

Step 2: configure the transaction scenario using the "tx: advice" label. Specifies the methods on which transactions are configured and the definitions of these transactions. Tx: advice contains one or more tx: attribtue, and tx: attribute contains one or more tx: method. Tx: The method label configures specific transactions.

Tx: The method attributes are

Example:

<Tx: advice id = "txAdvice"> <tx: attributes> <! -- The transaction whose method name starts with get is a read-only transaction, and the isolation level is SERIALIZABLE --> <tx: method name = "get *" read-only = "true" isolation = "SERIALIZABLE"/> <! -- The transaction whose method name starts with insert. The isolation level is SERIALIZABLE, and the propagation mechanism is REQUIRED. When TestException occurs, ArithmeticException will not roll back the transaction. --> <Tx: method name = "insert *" isolation = "SERIALIZABLE" timeout = "20" propagation = "REQUIRED" rollback-for = "com. rain. exception. testException "no-rollbackfor =" java. lang. arithmeticException "/> <tx: method name =" * "isolation =" READ_COMMITTED "/> </tx: attributes> </tx: advice>

Step 3: configure the transaction aspect through aop: config. Aop: config contains one or more (aop: pointcut, aop: advisor ). Aop: pointcut specifies the configuration section for which classes. aop: advisor associates tx: advice with aop: pointcut. The expression format in the aop: config label is execution (* packageName. className .*(..)). It is a SPEL expression.

Example:

<aop:config>    <aop:pointcut expression="execution(* com.rain.service.*.*(..))"  id="studentServiceMethod" />    <aop:advisor advice-ref="txAdvice" pointcut-ref="studentServiceMethod" /></aop:config> 

If multiple transactions are configured, repeat the preceding steps. You can also configure multiple groups in aop: config (aop: pointcut, aop: advisor ).

Step 4: verify. Use Log4J logs to set the level to DEBUG. The transaction configuration is loaded at startup.

2017-05-30 12:22:00 DEBUG NameMatchTransactionAttributeSource:96 - Adding transactional method [get*] with attribute [PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED,readOnly]2017-05-30 12:22:00 DEBUG NameMatchTransactionAttributeSource:96 - Adding transactional method [insert*] with attribute [PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,timeout_20,-com.rain.exception.TestException,+java.lang.ArithmeticException]2017-05-30 12:22:00 DEBUG NameMatchTransactionAttributeSource:96 - Adding transactional method [*] with attribute [PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED]

When running the insertXX method, the detailed process of transaction processing is displayed.

2017-05-30 11:49:57 DEBUG DataSourceTransactionManager:367 - Creating new transaction with name [com.rain.service.impl.StudentServiceImpl.insertStudent]: PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,timeout_20,-com.rain.exception.TestException,+java.lang.ArithmeticException。2017-05-30 11:49:58 TRACE TransactionInterceptor:517 - Completing transaction for [com.rain.service.impl.StudentServiceImpl.insertStudent] after exception: java.lang.ArithmeticException: / by zero2017-05-30 11:49:58 TRACE RuleBasedTransactionAttribute:131 - Applying rules to determine whether transaction should rollback on java.lang.ArithmeticException: / by zero2017-05-30 11:49:58 TRACE RuleBasedTransactionAttribute:148 - Winning rollback rule is: NoRollbackRuleAttribute with pattern [java.lang.ArithmeticException]2017-05-30 11:49:58 DEBUG DataSourceTransactionManager:759 - Initiating transaction commit2017-05-30 11:49:58 DEBUG DataSourceTransactionManager:310 - Committing JDBC transaction on Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@25df00a0]2017-05-30 11:49:58 TRACE TransactionSynchronizationManager:331 - Clearing transaction synchronization

When the insertXX method has a java. lang. ArithmeticException exception. Transactions are not rolled back.

2017-05-30 12:09:17 TRACE RuleBasedTransactionAttribute:131 -
Applying rules to determine whether transaction should rollback on java.lang.ArithmeticException: / by zero2017-05-30 12:09:17 TRACE RuleBasedTransactionAttribute:148 - Winning rollback rule is: NoRollbackRuleAttribute with pattern [java.lang.ArithmeticException]

When TestException is found in the insertXX method. Roll back the transaction.

Applying rules to determine whether transaction shocould rollback on com. rain. exception. testException: this is an exception for testing. 12:22:01 TRACE RuleBasedTransactionAttribute: 148-Winning rollback rule is: RollbackRuleAttribute with pattern [com. rain. exception. testException] 12:22:01 DEBUG DataSourceTransactionManager: 851-Initiating transaction rollback2017-05-30 12:22:01 DEBUG DataSourceTransactionManager: 325-Rolling back JDBC transaction on Connection [com. mchange. v2.c3p0. impl. newProxyConnection @ aba625]
Annotation Method

Step 1: Configure transaction management. It is exactly the same as declarative transactions. Step 1 of configuration section

Step 2: configure the transaction support annotation mode through tx: annotation-driven. Tx: annotation-driven attributes are

Example:

<! -- Configure annotation driver --> <tx: annotation-driven transaction-manager = "transactionManager" mode = "proxy" proxy-target-class = "true"/>

Step 3: add the @ Transactional annotation to the method. The meaning of the annotation attribute is as follows:

    @Transactional(propagation=Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE,timeout=20,rollbackFor = {com.rain.exception.TestException.class},            noRollbackFor = {java.lang.ArithmeticException.class})

Step 4: verify. When running this method. It loads the transaction attributes and creates the transaction.

2017-05-30 14:06:57 DEBUG AnnotationTransactionAttributeSource:116 - 
Adding transactional method 'com.rain.service.impl.StudentServiceImpl.insertStudent' with attribute: PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE; '',-com.rain.exception.TestException,-java.lang.NullPointerException,+java.lang.ArithmeticException2017-05-30 14:06:57 DEBUG DataSourceTransactionManager:367 -
Creating new transaction with name [com.rain.service.impl.StudentServiceImpl.insertStudent]: PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE; '',-com.rain.exception.TestException,-java.lang.NullPointerException,+java.lang.ArithmeticException

When TestException occurs, the transaction is rolled back.

14:06:57 TRACE RuleBasedTransactionAttribute: 131-Applying rules to determine whether transaction shold rollback on com. rain. exception. testException: this is an exception for testing. 14:06:57 TRACE RuleBasedTransactionAttribute: 148-Winning rollback rule is: RollbackRuleAttribute with pattern [com. rain. exception. testException]

Transactions are not rolled back when ArithmeticException occurs.

2017-05-30 12:09:17 TRACE RuleBasedTransactionAttribute:131 - Applying rules to determine whether transaction should rollback on java.lang.ArithmeticException: / by zero2017-05-30 12:09:17 TRACE RuleBasedTransactionAttribute:148 - Winning rollback rule is: NoRollbackRuleAttribute with pattern [java.lang.ArithmeticException]
Code Method

There are two methods for code to implement transactions. One is TransactionTemplate, which can be used to set transaction attributes. Another method is TransactionManager. TransactionManager can refer to the sample code below the core object.

TransactionTemplate Method

Step 1: Initialize TransactionTemplate,

1 // create a transaction template Class 2 private final TransactionTemplate tranTemp; 3 4 // create a student's service class 5 @ Autowired 6 private IStudentService studentService; 7 8 // initialize TransactionTemplate 9 public TransactionServiceImpl (PlatformTransactionManager tranManager) {10 Assert in the constructor. notNull (tranManager, "The 'tranmanager' argument must not be null"); 11 this. tranTemp = new TransactionTemplate (tranManager); 12}

Step 2: Call the execute method of transactionTemplate. The parameter is TransactionCallback or TransactionCallbackWithoutResult. The former returns void and the latter has a return type.

No returned TransactionCallbackWithoutResult

1 // implement transaction 2 @ Override 3 public void insertStudent (Student stu) {4 tranTemp.exe cute (new TransactionCallbackWithoutResult () {5 @ Override 6 protected void doInTransactionWithoutResult (TransactionStatus status) {7 try {8 // code logic 9} catch (Exception e) {10 e. printStackTrace (); 11 status. setRollbackOnly (); 12} 13} 14}); 15}

TransactionCallback <T>

1 public void insertStudentWithReturn (Student stu) 2 {3 tranTemp.exe cute (new TransactionCallback <Student> () {4 @ Override 5 public Student doInTransaction (TransactionStatus status) {6 try 7 {8 // code logic 9} catch (Exception e) 10 {11 e. printStackTrace (); 12 // roll back the transaction 13 status. setRollbackOnly (); 14} 15 return stu; 16}); 17}

This article ends

Related Article

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.