Spring things configuration, declarative transaction management, and usage based on @transactional annotations

Source: Internet
Author: User
Tags throwable

The management of things is essential for enterprise applications, so that anomalies can occur, and it also guarantees data consistency.

Spring supports both programmatic transaction management and declarative transaction management.

Programmatic transaction management uses Transactiontemplate or uses the underlying platformtransactionmanager directly. For programmatic transaction management, Spring recommends the use of transactiontemplate.

Declarative transaction management is built on the AOP. The essence is to intercept the method before and after it, and then create or join a transaction before the target method starts, committing or rolling back the transaction according to execution after the target method is executed. The greatest advantage of declarative transactions is that you do not need to programmatically manage transactions, so that you do not need to doping transaction-managed code in your business logic code, just make relevant transaction rule declarations in the configuration file (or through @transactional annotations). You can apply transaction rules to the business logic.

It is obvious that declarative transaction management is better than programmatic transaction management, which is the non-intrusive development approach advocated by spring. Declarative transaction management makes business code non-polluting, a common Pojo object that can be fully transactional supported with annotations. The only disadvantage of declarative transactions, compared to programmatic transactions, is that the finer granularity of the latter only works at the method level and cannot be scoped to the code block as a programmatic transaction. But even with this requirement, there are many workarounds, such as the ability to separate code blocks that require transaction management into methods, and so on.

There are two common ways of declarative transaction management, one is an XML configuration file based on the TX and AOP namespaces, and the other is based on @transactional annotations. The annotation-based approach is obviously easier to use and more refreshing.

Spring Transaction Features

Spring all transaction management policy classes inherit from the Org.springframework.transaction.PlatformTransactionManager interface

Where the Transactiondefinition interface defines the following features:

Transaction ISOLATION LEVEL

Isolation level refers to the degree of isolation between several concurrent transactions. Five constants representing the isolation level are defined in the Transactiondefinition interface:

    • Transactiondefinition.isolation_default: This is the default value that represents the default isolation level for using the underlying database. For most databases, this value is usually transactiondefinition.isolation_read_committed.
    • Transactiondefinition.isolation_read_uncommitted: This isolation level indicates that one transaction can read data that has been modified by another transaction but has not yet been committed. This level does not prevent dirty reads, non-repeatable reads, and Phantom reads, so the isolation level is rarely used. For example, PostgreSQL does not actually have this level.
    • Transactiondefinition.isolation_read_committed: This isolation level indicates that a transaction can only read data that has been committed by another transaction. This level prevents dirty reads, which is the recommended value in most cases.
    • Transactiondefinition.isolation_repeatable_read: This isolation level indicates that a transaction can repeatedly execute a query multiple times throughout the process, and that the records returned are the same each time. This level protects against dirty reads and non-repeatable reads.
    • Transactiondefinition.isolation_serializable: All transactions are executed one after the other, so that there is absolutely no possibility of interference between transactions, that is, the level prevents dirty reads, non-repeatable reads, and Phantom reads. However, this will severely affect the performance of the program. This level is not normally used.

Transactional propagation behavior

The so-called transaction propagation behavior is that if a transaction context already exists before the current transaction is started, there are several options to specify the execution behavior of a transactional method. The transactiondefinition definition includes the following constants that represent propagation behavior:

    • Transactiondefinition.propagation_required: If a transaction is currently present, the transaction is joined and a new transaction is created if there is no current transaction. This is the default value.
    • Transactiondefinition.propagation_requires_new: Creates a new transaction and suspends the current transaction if a transaction is currently present.
    • Transactiondefinition.propagation_supports: If a transaction is currently present, the transaction is joined, and if no transaction is currently present, it will continue in a non-transactional manner.
    • Transactiondefinition.propagation_not_supported: Runs in a non-transactional manner, suspending the current transaction if a transaction is currently present.
    • Transactiondefinition.propagation_never: Runs in a non-transactional manner and throws an exception if a transaction is currently present.
    • Transactiondefinition.propagation_mandatory: If a transaction is currently present, the transaction is joined and an exception is thrown if there is no current transaction.
    • Transactiondefinition.propagation_nested: If a transaction is currently present, create a transaction to run as a nested transaction for the current transaction, or if there is no current transaction, The value is equivalent to transactiondefinition.propagation_required.

Transaction timeout

The so-called transaction timeout is the maximum time a transaction is allowed to execute, and if the time limit is exceeded but the transaction is not completed, the transactions are automatically rolled back. The value of int in transactiondefinition represents the time-out, in seconds.

The default setting is the timeout value for the underlying transaction system, or none if the underlying database transaction system does not have a timeout value set.

Transactional read-only properties

Read-only transactions are used in situations where the client code is read-only but does not modify the data, and read-only transactions are used for optimizations under specific scenarios, such as when using Hibernate. The default is read-write transactions.

A read-only transaction is not a mandatory option, it is simply a hint that prompts the database driver and the database system that does not contain changes to the data, and that the JDBC driver and database are likely to perform some specific optimizations for that transaction, such as not scheduling the corresponding database lock. To mitigate the stress of transactions on the database, after all, the transaction also consumes the resources of the database.

But you have to modify the data in the "read-only Transaction", and it is not, but the protection of data consistency is not as safe as read-write transactions.

Therefore, "read-only Transaction" is only a recommended configuration for performance optimization, not forcing you to do so

Spring Transaction rollback rules

The recommended way to instruct the spring transaction manager to roll back a transaction is to throw an exception within the context of the current transaction. The spring transaction manager catches any unhandled exceptions, and then determines whether the transaction that throws the exception is rolled back according to the rule.

By default, spring rolls back the transaction only if the exception is thrown as a run-time unchecked exception, which is the subclass of RuntimeException that throws the exception (errors also causes the transaction to be rolled back), while throwing a checked exception does not cause the transaction to be rolled back. Can be explicitly configured to roll back transactions when those exceptions are thrown, including checked exceptions. You can also explicitly define those exceptions that are thrown without rolling back the transaction. You can also programmatically use the Setrollbackonly () method to indicate that a transaction must be rolled back, and that the only action you can perform after the call to Setrollbackonly () is to rollback.

    • MyBatis as an example annotation-based declarative transaction management configuration @transactional

Spring.xml

<span style= "" ><span style= "" ><!--mybatis config--><bean id= "sqlsessionfactory" class= " Org.mybatis.spring.SqlSessionFactoryBean "><property name=" DataSource "ref=" DataSource "/><property Name= "Configlocation" ><value>classpath:mybatis-config.xml</value></property></bean> <!--MyBatis Mappers, scanned automatically--><bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "><property name=" Basepackage "><value> Com.baobao.persistence.test</value></property><property name= "SqlSessionFactory" ref= " Sqlsessionfactory "/></bean><!--Configure Spring Platformtransactionmanager with the default value--><bean id=" TransactionManager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property Name= "DataSource" ref= "DataSource"/></bean><!--enable annotation support for transaction control--><tx:annotation-driven Transaction-manager= "TransactionManager"/></span></span>

Adding a TX namespace

<span style= "" ><span style= "" >xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "/HTTP/ Www.springframework.org/schema/tx "xsi:schemalocation=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/http Www.springframework.org/schema/aop/spring-aop-3.0.xsd    HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-3.0.xsd "</span></span>


MyBatis automatically participates in spring transaction management without the need for additional configuration, Transaction management will not work as long as the data source referenced by Org.mybatis.spring.SqlSessionFactoryBean is consistent with the data source referenced by Datasourcetransactionmanager.

@Transactional annotations

@Transactional Properties

Properties type Description
Value String Optional qualifier descriptor, specifying the transaction manager to use
Propagation Enum:propagation Optional transaction propagation behavior settings
Isolation Enum:isolation Optional Transaction ISOLATION Level setting
ReadOnly Boolean Read-write or read-only transactions, default read and write
Timeout Int (in seconds granularity) Transaction time-out time setting
Rollbackfor Class object array, must inherit from Throwable An array of exception classes that cause transaction rollback
Rollbackforclassname Class An array group, must inherit from Throwable An array of exception class names that caused the transaction rollback
Norollbackfor Class object array, must inherit from Throwable An array of exception classes that will not cause the transaction to be rolled back
Norollbackforclassname Class An array group, must inherit from Throwable An array of exception class names that will not cause the transaction to be rolled back

Usage

@Transactional can be used on interfaces, interface methods, classes, and class methods. When used on a class, all public methods of the class will have transactional properties of that type, and at the method level we can also use the callout to override the class-level definition.

Although @Transactional annotations can be used on interfaces, interface methods, classes, and class methods, Spring does not recommend using this annotation on an interface or interface method, because it takes effect only when using an interface-based proxy. In addition, @Transactional annotations should only be applied to the public method, which is determined by the nature of Spring AOP. If you use @Transactional annotations on protected, private, or default visibility methods, this is ignored and no exceptions are thrown.

By default, only method calls from outside are captured by the AOP proxy, which means that other methods inside the class that call this class do not cause transactional behavior, even if the called method uses @transactional annotations to decorate.

@Autowiredprivate Mybatisdao dao; @Transactional @overridepublic void Insert (test test) {Dao.insert (test); throw new RuntimeException ("test");//Throw unchecked exception, trigger things, rollback}

Norollbackfor

@Transactional (norollbackfor=runtimeexception.class) @Overridepublic void Insert (test test) {Dao.insert (test);// Throws a unchecked exception, triggers a thing, norollbackfor=runtimeexception.class, does not roll back the throw new RuntimeException ("test");

Class, when used on a class, all public methods of the class will have transaction properties of that type

@Transactionalpublic class Mybatisserviceimpl implements Mybatisservice {@Autowiredprivate Mybatisdao dao;@ overridepublic void Insert (test test) {Dao.insert (test);//throws a unchecked exception, triggers the thing, rolls back the throw new RuntimeException ("Test");}

propagation=propagation.not_supported

@Transactional (propagation=propagation.not_supported) @Overridepublic void Insert (test test) {//Thing propagation behavior is propagation_ Not_supported, run in a non-transactional manner, will not be stored in database Dao.insert (test);}
    • MyBatis as an example annotation-based declarative transaction management configuration, XML configuration

Mainly for AOP facets configuration, just look at the XML can be

<!--things facets configuration--><tx:advice id= "advice" transaction-manager= "TransactionManager" ><tx:attributes> <tx:method name= "update*" propagation= "REQUIRED" read-only= "false" rollback-for= "Java.lang.Exception"/>< Tx:method name= "Insert" propagation= "REQUIRED" read-only= "false"/></tx:attributes></tx:advice>< Aop:config><aop:pointcut id= "Testservice" expression= "Execution (* com.baobao.service.mybatisservice.* (..))" /><aop:advisor advice-ref= "Advice" pointcut-ref= "Testservice"/></aop:config>

Spring things configuration, declarative transaction management, and usage based on @transactional annotations

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.