Spring Transaction control

Source: Internet
Author: User
Tags savepoint time limit

In real business scenarios, we often encounter problems with frequent data modification reads. At the same time, different business logic modifies the same table data, which is likely to cause data irreparable confusion, so we need to manage the data with a transaction.

1. What is a business?

I think that at the same moment, we take a few different things as one thing to do, either all succeed or all fail this is the business;

2. Characteristics of the transaction (ACID)

atomicity: The smallest execution unit of a transaction, which does not allow splitting. The atomicity of the transaction ensures that the instructions are either completed or all fail;

Consistency: The data is consistent before and after the execution of the transaction, and the execution of the transaction causes the data to transition from one state to another, but the integrity of the data remains stable;

Isolation: When accessing a database concurrently, a user's things are not disturbed by other things, and the database is independent between the concurrent transactions.

Persistence : After a transaction is committed, its changes to the data in the database are persistent, and should not have any effect on the database if it fails;

3. Problems caused by concurrent transactions

In our application, it is common for multiple transactions to run concurrently, while manipulating the same data to solve business problems, this can cause some of the following problems:

  Dirty Reads (Dirty read): when a transaction is accessing the data and modifying the data, and the modification has not yet been committed to the database, another transaction accesses the data and then uses that data.

Because this data is data that has not yet been submitted, the data that is read by another transaction is "dirty", and the operation based on "dirty data" may not be correct.

lost Modification (Lost to modify): refers to when one transaction reads one data, another transaction accesses the data, then the second transaction modifies the data after the first transaction has been modified.

Thus, the result of the modification within the first transaction is lost, so it is called a lost modification.

non-repeatable Read (Unrepeatableread):    refers to reading the same data multiple times within a transaction. When the transaction has not ended, another transaction accesses the data. So, between the two read data in the first transaction,

Because the modification of the second transaction causes the first transaction to read two times, the data may not be the same. This occurs when the data that is read two times within a transaction is not the same, and therefore is called non-repeatable read.

  Phantom Read (Phantom Read): Phantom reads are similar to non-repeatable reads. It occurs when a transaction (T1) reads a few rows of data, and then another concurrent transaction (T2) inserts some data. In the subsequent query,

The first transaction (T1) will find a number of records that do not exist, as if there were hallucinations, so called Phantom Reading.

The difference between non-repeatability and Phantom reads:

The emphasis of non-repeatable reading is to modify, and the focus of phantom reading is to add or delete.

4. Spring Transaction Manager Interface Platformtransactionmanager

The so-called transaction management, in fact, is "to follow the given transaction rules to commit or rollback operations." Spring does not directly manage transactions, but rather provides a variety of transaction managers who delegate the responsibility of transaction management to the transactions of the relevant platform framework provided by the persistence mechanism such as Hibernate or JTA.

The interface of the spring transaction manager is: Org.springframework.transaction.PlatformTransactionManager , with this interface, spring for each platform such as JDBC, Hibernate provides the corresponding transaction manager, but the specific implementation is the individual platform of their own things.

Package Org.springframework.transaction;import Org.springframework.lang.nullable;public Interface Platformtransactionmanager {        //based on the specified propagation behavior, returns the currently active transaction or creates a new transaction Transactionstatus gettransaction (@ Nullable transactiondefinition definition) throws TransactionException;        Commit TRANSACTION void commit (Transactionstatus status) throws TransactionException using the current state of the transaction;        Rollback of the executed transaction to void rollback (Transactionstatus status) throws TransactionException;}

Spring Platformtransactionmanager implements classes according to the interface of the different persistence layer frameworks, several more common as shown in

5. Transaction attribute Interface Transactiondefinition

The interface of spring transaction properties is: org.springframework.transaction.TransactionDefinition , transaction properties can be understood as some basic configuration of a transaction, Describes how transaction policies are applied to methods.

Package Org.springframework.transaction;import Java.sql.connection;import org.springframework.lang.Nullable; Public interface Transactiondefinition {        //propagation behavior int getpropagationbehavior ();        The isolation level under which the transaction manager controls which data in this transaction can be seen by the other transaction int getisolationlevel ();        Transaction Timeout int gettimeout ();        Whether to read-only Boolean isreadonly ();        Returns the name of the transaction @nullablestring GetName ();}

Transaction properties contain five aspects: propagation behavior, isolation level, transaction timeout, and regression rule, whether read-only.

(1) Transaction isolation level (defines the extent to which a transaction may be affected by other concurrent transactions):

Five constants representing the isolation level are defined in the Transactiondefinition interface:

    • Transactiondefinition.isolation_default: using the default isolation level of the backend database, Mysql defaults to the Repeatable_read isolation level Oracle defaults to Read_ Committed isolation level.
    • transactiondefinition.isolation_read_uncommitted: lowest isolation level, allowing reading of data changes that have not yet been committed, may result in dirty reads, Phantom reads, or non-repeatable reads
    • transactiondefinition.isolation_read_committed: allows reading of data that has been committed by concurrent transactions to prevent dirty reads, but phantom or non-repeatable reads can still occur
    • Transactiondefinition.isolation_repeatable_read: Multiple read results for the same field are consistent unless the data is modified by itself and can prevent dirty reads and non-repeatable reads. But Phantom reading can still happen.
    • transactiondefinition.isolation_serializable: highest isolation level, fully compliant with acid isolation level. 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.
(2) Transactional propagation behavior (in order to resolve transaction issues that are invoked between business layer methods):

When a transaction method is called by another transaction method, you must specify how the transaction should propagate. For example: The method might continue to run in an existing transaction, or it might open a new transaction and run in its own transaction. The transactiondefinition definition includes the following constants that represent propagation behavior:

Scenarios that support the current transaction:

      • 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.

      • 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_mandatory: If a transaction is currently present, the transaction is joined and an exception is thrown if there is no current transaction.

Cases where the current transaction is not supported:

      • transactiondefinition.propagation_requires_new: creates a new transaction and suspends the current transaction if a transaction is currently present.

      • 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.

Other information:

      • 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.

It should be noted here that the previous six transactional propagation behaviors were introduced by Spring from the EJB and shared the same concepts. and propagation_nested is unique to Spring. A propagation_nested-initiated transaction is embedded in an external transaction (if there is an external transaction), at which point the inline transaction is not a separate transaction, it relies on the existence of the external transaction, and only commits the external transaction to cause the internal transaction to be committed. Nested child transactions cannot be submitted separately. If you are familiar with the concept of savepoint (savepoint) in JDBC, then nested transactions are easy to understand, in fact, nested sub-transactions is an application of the savepoint, a transaction can include multiple savepoint, each nested child transaction. Also, a rollback of an external transaction results in a rollback of the nested transaction.

(3) Transaction Timeout property (maximum time a transaction is allowed to execute)

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.

(4) Transaction read-only property (whether a read-only operation is performed on a thing Resource)

A read-only property of a transaction is a read-only operation on a transactional resource or a read-write operation. A transactional resource is a resource that is managed by a transaction, such as a data source, a JMS resource, a custom transactional resource, and so on. If you determine that only transactional resources are read-only, then we can flag the transaction as read-only to improve the performance of transaction processing. A Boolean type in Transactiondefinition that indicates whether the transaction is read-only.

(5) Rollback rule (define transaction rollback rules)

These rules define which exceptions cause transactions to be rolled back and which do not. By default, transactions are rolled back only when they encounter a run-time exception, and are not rolled back when encountering a check exception (this behavior is consistent with the rollback behavior of the EJB). However, you can declare that a transaction is rolled back as if it encountered a run-time exception when it encounters a particular check-type exception. Similarly, you can also declare that a transaction encounters a particular exception without rolling back, even if the exception is a run-time exception.

6. Transaction Run State interface Transactionstatus

The interface of the spring transaction running state is: org.springframework.transaction.TransactionStatus, which defines a set of methods used to obtain or determine the appropriate state information for a transaction.

The Platformtransactionmanager.gettransaction (...) method returns a Transactionstatus object. The returned Transactionstatus object may represent a new or already existing transaction (if there is a qualifying transaction on the current call stack).

Package Org.springframework.transaction;import Java.io.flushable;public Interface Transactionstatus extends Savepointmanager, flushable {        //Is the new Thing Boolean isnewtransaction ();        Whether there is a recovery point Boolean hassavepoint ();        Set to rollback only void setrollbackonly ();        Whether to roll back only the Boolean isrollbackonly ();        Clear @overridevoid Flush ();        Whether the Boolean iscompleted () has been completed;

  

Spring Transaction control

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.