Four characteristics of database transactions, isolation levels, and how to use AOP for transaction management in spring database

Source: Internet
Author: User
Tags aop rollback

first, what is a transaction.

A transaction is a logical unit of business that ensures that all operations on the data are successful or fail.

second, what are the characteristics of the transaction?

1. Atomic sex.

For example, transfer, a reduced account, B account increase. Although it is a two DML statement, it is treated as a whole, one transaction at a time. Two statements can only succeed at the same time or fail at the same time.

2. Consistency.

Accounts A and B are either the state before the transfer or the state after the transfer. (The money for a account is reduced but the B account does not increase).

3. Isolation.

Although a lot of people are transferring money during a certain time period, each person's transfer is in one's own affairs and will not affect each other.

4. Durability.

After the transaction is committed successfully, the data changes will always take effect.

before considering the isolation level of a transaction, it is necessary to recognize the exception that occurs if the isolation of the transaction is not considered:

1. Dirty Reading

One transaction read data that was not committed by another transaction. (There is a lot of potential for concurrent processing of the system)

2. Non-repeatable reading

Within the same transaction, when reading the same data multiple times, the data was found to have been modified by another committed transaction. (data that is read two times within a transaction is not the same.) )

3. Phantom Reading

A transaction executes a query based on the same query criteria, and the returned record contains a row that differs from the record returned by the previous execution query.


All three of these cases are caused by simultaneous reading of the same data by several transactions.

How to deal with these kinds of anomalies.

The following transaction isolation levels are defined in the ANSI SQL-92 standard:

1.Read UNCOMMITTED

The lowest level of transaction isolation, which only guarantees that no illegal data is read during the read process. (Three kinds of anomalies can occur)

2.Read committed

"Dirty reads" are avoided. A select query can only view data that was submitted before the query started. When the query executes, the other transaction modifies or submits the data it does not see (database default transaction ISOLATION level)

3.Repeatable Read

"Dirty read" and "not repeatable read" are avoided. It is not possible for one transaction to update data that was read by another transaction but not submitted. Application is not widespread. Because it can have phantom reads. It also leads to more performance losses.

4.Serializable

The Oracle database supports only the Read committed and serializable two isolation levels. In addition, the isolation level of a read only is defined, which is only allowed to read and not allowed to be changed. Avoid non-repeatable reading and Phantom reading

Three of them can be avoided. All transactions are serial, not parallel.

Isolation level of spring transaction
1. Isolation_default: This is a platfromtransactionmanager default isolation level that uses the default transaction isolation level of the database.
The other four levels of isolation from JDBC correspond to
2. Isolation_read_uncommitted: This is the lowest isolation level for a transaction, which allows an external transaction to see uncommitted data for this transaction.
This isolation level produces dirty reads, no repeat reads, and Phantom reads.
3. isolation_read_committed: Ensure that a transaction modified by the data submitted before being read by another transaction. Another transaction cannot read data that is not committed by the transaction
4. Isolation_repeatable_read: This transaction isolation level prevents dirty reads and cannot be read repeatedly. However, Phantom reads may occur.
In addition to ensuring that one transaction cannot read data that is not committed by another transaction, it also ensures that the following conditions are avoided (non-repeatable reads).
5. Isolation_serializable This is the highest cost but the most reliable level of transaction isolation. Transactions are processed for sequential execution.
In addition to preventing dirty reading, it is not repeatable to read, but also avoid phantom reading.

implementing declarative transaction Management with spring AOP

1. Based on XML configuration (more usage)

(1) Configure the Transaction management class

<!--define the transaction manager-->
<bean id= "TransactionManager
class=" Org.springframework.jdbc.datasource.DataSo Urcetransactionmanager ">
<property name=" DataSource "ref=" DataSource "/>
</bean>
Configuring the data source (DataSource) and transaction manager in spring configuration, the transaction manager uses different ORM Framework transaction manager classes, MyBatis is Org.springframework.jdbc.datasource.DataSourceTransactionManager. And the Hibernate transaction manager is Org.springframework.orm.hibernate3.HibernateTransactionManager

(2) Configure transaction properties

<!--  Configuring transaction Properties  -->       <tx:advice id= "Testadvice"   Transaction-manager= "TransactionManager" >           <!- -Configure issues such as transactional propagation, isolation level, and timeout rollback  -->   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TX: attributes>   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;TX: Method name= "search*"  propagation= "REQUIRED" read-only= "true" isolation= "Defaut" timeout= "-1"  / >               <tx:method  Name= "del*"  propagation= "REQUIRED"  />           
    <tx:method name= "update*"  propagation= "REQUIRED"  />               <tx:method name= "add*"   propagation= "REQUIRED"  />           </tx:attributes>        </tx:advice>

Transaction properties are set in <tx:method>, and spring supports different transaction attributes for different methods, so you can set multiple <tx:method> for a <tx:advice>; Where the Name property specifies a matching method (where the method names are required to be specified, and if the transaction pointcut is on the service, it is best to distinguish it from the DAO's method name, and not to use the Get Set keyword to prevent confusion with the getter setter of the property)

transactions have several common properties:

A.read-only: Sets whether the data is allowed to be modified in this transaction. (setting to True for transactions that perform only the query function can increase the speed at which transactions are performed)

B.propagation: The communication mechanism of the business. The general setting is required. You can guarantee that code in a transaction runs only in the current transaction, preventing multiple transactions from being created.

C.isolation: Transaction ISOLATION level. is not a necessity. Defaults are default values.

D.timeout: The maximum time, in seconds, that a transaction is allowed to run.

E.rollback-for: The exception that triggers the rollback.

F.no-rollback-for: The exception that does not trigger a rollback.

In actual development, to set Read-only to true for transactions that only perform query functions, other properties typically use the default values.


(3) AOP pointcut for configuring transactions

<aop:config>
<!--configure transaction pointcuts-->
<aop:pointcut id= "Services"
Expre ssion= "Execution (public* com.pb.service.*.* (..))"/> <aop:advisor pointcut-ref=
"Services" advice-ref= " Testadvice "/>
</aop:config>

This setting means that all public methods of the Com.pb.service.impl package and all classes under the child package are cut into. The most appropriate transaction entry point for a Web application is the method of service (through <tx:method> filter).

----After you set up a declarative transaction with the above three steps, spring obtains the transaction object and starts the transaction before the business method in the service is invoked. and use try-catch-finally to handle exceptions. Successful execution of the business method commits the transaction, which by default rolls back the transaction if the RuntimeException or Rrror object is thrown. (Note: Note here that the rollback_for configured in the Tx:method is configured in exception this is a Run-time exception that will be rolled back or other exceptions will not be rolled back.) )

2. Use annotation configuration

*1. Mark @transactional before the DAO implementation class for the transaction management

*2. Add @transactional (propagation= propagation.required) before the method for transaction management

*3. Specify the driver in the configuration file: <tx:annotation-driven transaction-manager= "TransactionManager"/>

Package Demo.spring.dao;

Import Java.util.Iterator;
Import java.util.List;

Import Javax.sql.DataSource;

Import org.springframework.jdbc.core.JdbcTemplate;
Import org.springframework.transaction.annotation.Propagation;
Import org.springframework.transaction.annotation.Transactional;

Import Demo.spring.entity.Person;
@Transactional//The transaction management of this class public
class Persondaoimpl implements Persondao {
	private jdbctemplate JT;
	
	public void Setdatasource (DataSource DataSource) {
		JT = new JdbcTemplate (DataSource);
	}
	@Override public
	void Insert (Long ID, String name, int age) {
		jt.update ("Insert to Person values" (' +id+ "', '" + Name+ "', '" "+age+") ");

	@Transactional (propagation= propagation.required)//Defines a method for transaction management, specifying the propagation behavior public
	void Batchinsert (List persons) { For
		(Iterator it = Persons.iterator (); It.hasnext ();) {person
			p = (person) it.next ();
			Insert (P.getid (), P.getname (), P.getage ());}}}

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.