Spring Declarative Transactions

Source: Internet
Author: User

The Spring Framework provides two ways to support transaction management1> Programmatic transactions: Transactiontemplate Class (recommended) for transaction management;2> declarative transactions based on the Platformtransactionmanager class: AOP-based implementations (dynamic proxy weaving transactions, committing/ ROLLBACK TRANSACTION), only need to configure the transaction rules in the configuration file (TX and AOP configuration or use @transactional annotations), annotated way to develop concise recommended use.
Programmatic transactions require manual processing of transaction opening, commit, rollback, increased development effort, finer transaction control, and can be a code block level in a method (declarative transactions can also implement the same functionality by separate code blocks into methods).
Declarative transactions are non-intrusive (common Java classes with annotations for transactional support), and the most granular of transaction control is the method level;
Transaction Implementation MechanismIn the BeginTransaction phase (the Hiberante framework is BeginTransaction (), the spring frame is dobegin ()), The spring underlying implementation sets the autocommit of the connection object to False, cancels autocommit, and then commits/rolls back in the endtransaction phase.
Transaction ISOLATION level (consistent with four levels of database)1>Transactiondefinition.isolation_default    # This is the default value, which indicates the default isolation level for using the underlying database. Most databases usually default to: Read_committed read has been submitted;2> transactiondefinition.isolation_read_uncommitted    # one transaction can read data that has been modified by another transaction but has not yet been committed. problem: This level does not prevent dirty reads, non-repeatable reads, and Phantom reads, so this isolation level is rarely used. For example, PostgreSQL does not actually have this level. 3> transactiondefinition.isolation_read_committed        # aa transaction can only read data that has been committed by another transaction. Can prevent dirty reads, which is the recommended value in most cases. 4> Transactiondefinition.isolation_repeatable_read      # a transaction can repeatedly execute a query multiple times throughout the process, and each return record is the same. can prevent dirty reads and non-repeatable reads. 5> transactiondefinition.isolation_serializable    # All transactions are executed one by one, so that there is absolutely no interference between transactions, which 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.
Dirty Reads (Dirty read):dirty reads occur when a transaction reads data that has been overwritten by another transaction but has not yet been committed. If these changes are rolled back later, then the data read by the previous transaction is invalid. non-repeatable read (nonrepeatable Read):non-repeatable reads occur when a transaction executes the same query two or more times or more than two times, but each time the query results are not the same. This is usually due to the fact that another concurrent transaction has updated data between two queries. Phantom Read (Phantom Read):Phantom Reading is when a transaction reads several rows of records, another transaction inserts some records, and the phantom reads occur. In later queries, the first transaction will find some additional records that were not originally available.
Transactional propagation behavior (transactiondefinition)1> propagation_mandatory    # the method must be running in a transaction. Throws an exception if the current transaction does not exist. 2> propagation_nested    # If a transaction is currently present, the method runs in a nested transaction. A nested transaction can be committed and rolled back separately from the current transaction. If the transaction does not currently exist, a new transaction is started. Each vendor's support for this type of communication is uneven and needs attention when used.  3> Propagation_never      # The current method should not run in a transaction. Throws an exception if there is currently a transaction. 4> propagation_not_supported    # The current method should not run in a transaction. If a transaction is running, it will hang during the run of the method. 5> propagation_required    # the method must be running in a transaction. If a transaction is running, the method will run in this transaction. Otherwise, a new transaction is started. 6>propagation_requires_new    # the method must be running in its own transaction. It will start a new transaction. If an existing transaction is running, it will be suspended during the run of this method. 7> propagation_supports    # the current method does not require a transactional environment, but this method can also run in this transaction if a transaction is already running.
@Transactional exception rollback policySpring defaults to a run-time exception (RuntimeException) for transaction rollback (unchecked), and does not roll back if it encounters checked unexpectedly. This default rule can be adjusted as follows:1>@Transactional (Rollbackfor=exception.class)                            # checked and unchecked exceptions are rolled back2>@Transactional (Notrollbackfor=runtimeexception.class)       # let unchecked exception not rollback (checked, unchecked do not rollback)
Spring transaction and thread safetyThe transaction of spring management is threadlocal,The server responds to each request with a new thread, and the transaction for each thread that corresponds to the request is completely threadlocal, that is, the transaction is completely and the thread wants to shut down, and the transaction rollback of one thread does not affect the other threads. database connection connection are not shared among different threads, and the transaction manager provides separate connection replicas for different transactional threads using the Threadlocal class. key Source (classes and methods):
Org.springframework.transaction.interceptor.TransactionInterceptor.invokeorg.springframework.transaction.interceptor.Tran Sactionaspectsupport.createtransactionifnecessary       # the Transactioninfoholder type isthreadlocal<transactioninfo>Org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction Conclusion:1> in spring, DAO and service are all in the form of single-instance beans, and spring uses the Threadlocal class to thread a stateful variable (such as a database connection connection) locally, enabling it to be secure in multithreaded situations. In a processing thread for a request response, the thread runs through the display, service, and data persistence layer three, through threadlocal so that all associated objects are referenced to the same variable. 2> when the transaction property is required, the transaction methods that make each other nested calls within the same thread work in the same transaction. Transaction methods under different threads work in separate transactions if the transaction method that nested the calls to each other is working in a different thread. 3> program as long as the use of Springdao templates, such as JdbcTemplate for data access, there must be no database connection leakage problem! If you explicitly get the data connection connection in your program, you need to close it manually, otherwise it will leak! 4> when the spring transaction method runs, a transaction context is generated that binds a unique data connection to the same data source in this transaction execution thread, and all methods propagated by the transaction context share the connection. To get this connection, use the SPIRNG resource to get the tool class Datasourceutils. The 5> transaction management context is like a box, where all the transactions are placed. If a new thread is opened in a transaction method and another transaction method is executed in the new thread, then the two methods above are known to run in two separate transactions, but: if you use Datasourcesutils, the methods in the new thread can get the data connections from the original thread from the transaction context!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Declarative Transactions

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.