Spring Transaction Summary---Transaction overview and Basic use of spring transactions (complete)

Source: Internet
Author: User
Tags aop rollback valid
I. Overview of transactions

This section is purely for writing and writing, right when the knowledge of the database and familiar with how to write a blog, who let their dishes. :)

Read a lot of other blogs and materials, business two words are fast not to know, then actually the concept of business is very simple, can be understood as one thing, in the computer, it is a sequence of operations.

It differs from ordinary things in that it must obey the acid principle specified by ISO/IEC.

A (aotomicity) atomicity, simply said to be either all done together, or do not do, that is, the indivisibility of the transaction, unless the use of special means, such as catch some sub-transaction exception, otherwise when one of the child transaction fails, other transactions will be rolled back together.

C (consistency) consistency, that is, its guarantee from a correct state, converted to another correct state, that is, after the operation of the data will not be destroyed, such as the transfer will not occur when one party has deducted the money and the other party cannot receive the situation.

I (Isolation) isolation, before a transaction commits, its possible results should not be displayed to other transactions. For example, if a transaction for a bank needs to deposit $100 after depositing 200 yuan, that of course, it can not be deposited in 100 yuan, on the instantiation of the database was read by other transactions to the result of 100 yuan, if the deposit of 200 yuan when the rollback is not a big deal. The so-called isolation is the need to ensure that there is no mutual interference between the various transactions.

D (durability) persistence, the result will be correctly persisted in the database, the failure of other transactions will not affect it.



The above four features are often discussed and argued for consistency and isolation. The so-called fish and bear can not have both, when we need to take into account all the characteristics, it can be imagined that when the higher the security, the more scruples and inspection of its operation, performance will be worse. So for consistency and isolation, there are different levels of specification. (Rubbish writing skills)

Tradeoffs that may arise under the problem

1, dirty read, that is, read the unclean data.

Example: (example site)

1) Mary's original salary was 1000, and the treasurer changed Mary's salary to 8000 (but did not commit the transaction)
2) Mary read her own salary and found her salary changed to 8000.
3) While the financial discovery operation was incorrect, the transaction was rolled back, and Mary's salary changed to 1000, like this, Mary remembered the wage number 8000 is a dirty data.

2, non-repeatable read, that is, in the same transaction, repeated reading has different results.

Example: (example site)

1) in transaction A, Mary reads her own salary of 1000, and the operation is not completed
2) in transaction B, the financial officer modified Mary's salary to 2000 and submitted the transaction.
3) in transaction A, when Mary reads her salary again, the salary becomes 2000

3, Phantom Reading, that is, in the same transaction, can read to other transactions after the submission of the results, causing confusion.

Example: (example site)

1) A change all "black" to "white"

2) b Change All "red" to "black"

3) A again query black, but found there are a batch.



Four levels of isolation

1, read_uncommited (Unauthorized read), that is, can read to uncommitted data.

Attach a vivid example of someone else's writing

The company paid, the leader of the 5000 yuan to the Singo account, but the transaction did not submit, and Singo just to check the account, found that the salary has been to the account, is 5000 yuan whole, very happy. Unfortunately, the leadership found that the amount of wages issued to Singo is not correct, is 2000 yuan, and then quickly rolled back to business, modify the amount, the transaction will be submitted, and finally singo the actual salary of only 2000 yuan, Singo empty joy a game. Site

2, read_commited (authorized read), that is, its guarantee will not read to uncommitted transactions, but will cause non-repeatable read.

Attach a vivid example of someone else's writing

Singo take the payroll card to spend, the system read to Cary really have 2000 yuan, and at this time her wife also just in the online transfer, the Singo Pay card of 2000 yuan to another account, and before Singo submitted the business, when Singo deduction, System Check to Singo's payroll card has no money, deduction failure, Singo very puzzled, obviously card money, why ...

The above situation, that is what we call non-repeatable read, two concurrent transactions, "transaction A:singo consumption", "Transaction B:singo wife online transfer", transaction A in advance read the data, transaction B immediately updated the data, and committed the transaction, and transaction a read the data again, The data has changed. Site
3, Repeatable_read (Repeatable read), that is, when reading, can not be updated.

Attach a vivid example of someone else's writing

When Singo took the payroll card to spend, once the system began to read the Payroll card information (that is, the start of the transaction), Singo's wife could not change the record, that is Singo wife can not be transferred at this time.

Although repeatable read avoids non-repeatable reads, it is possible to have phantom reads.

Singo's wife works in the banking department, and she often views Singo's credit card consumption records through the internal banking system. One day, she was inquiring into the total consumption amount of credit card in Singo month (select SUM (amount) from transaction where month = this month) was $80, and Singo at this time was good to eat outside the sea plug at the cashier to pay, spend 1000 yuan , which adds a $1000 consumption record (insert transaction ... ), and submitted a transaction, then Singo's wife will singo the current month credit card consumption details printed to A4 paper, but found that the total consumption of 1080 yuan, Singo wife is very surprised, thought there was an illusion, the illusion of such a generation.

Note: The default isolation level for MySQL is repeatable read. Site

4, SERIALIZABLE (serialized), highest level, at this level, the transaction order execution, then there is no problem.

These four specifications, from top to bottom, the higher the security, the worse the performance.

With a table that can be seen anywhere.

Transaction ISOLATION level Dirty read non-repeatable read Phantom read
Read_uncommited y y
read_commited N y y
Repeatable_read N N Y
SERIALIZABLE n n N




Two, spring transaction usage

1, XML configuration (handling summary from the open-Tao great God)

The core of <!--transaction management is transaction manager abstraction, which enables transaction management of a variety of data access frameworks (such as Hibernate) through the implementation of the policy interface Platformtransactionmanager.
<bean id= "Txmanager"
class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name= "Sessionfactory" ref= "Sessionfactory"/>
</bean>

<tx:advice transaction-manager= "Txmanager" id= "Txadvice" >
<tx:attributes>
<!--means that the method that starts with add will be intercepted, and the intercepted method will apply the configured transaction properties: Propagation represents the propagation behavior level, by default required,isolation represents the isolation level
Name: Defines the method name associated with the transaction property, applies the defined transaction properties to the matching method, and can use the "*" wildcard character to match a set or all of the methods, such as "save*" will match the method beginning with Save, and "*" will match all methods;
Propagation: The transaction propagation behavior definition, which defaults to "REQUIRED", represents REQUIRED, whose value can be specified by the "Propagation_" part of the static propagation behavior variable of transactiondefinition, such as " Transactiondefinition.propagation_required "can be specified with" REQUIRED ";
Isolation: The transaction isolation level is defined, default is "defaults", and its value can be specified by the "Isolation_" section of the Transactiondefinition static isolation level variable, such as " Transactiondefinition. Isolation_default "DEFAULT" can be used to specify:
Timeout: Transaction time-out setting, in seconds, Default-1, indicating that transaction timeouts will depend on the underlying transaction system;
Read-only: Transaction read-only setting, default = False, indicates not read-only;
Rollback-for: The exception definition that needs to trigger rollback, with "," split, default any runtimeexception will cause the transaction to be rolled back, and any checked Exception will not cause the transaction to be rolled back ; The definition of the exception name is the same as in Transactionproxyfactorybean
No-rollback-for: Exception (s) not triggered for rollback, split with ",", exception name definition and transactionproxyfactorybean meaning;
<tx:method name= "add*"/>
<:attributes>
<:advice>

<aop:config>
<!--pointcut definition, defines a aspectj pointcut named "Mypointcut", and the pointcut expression is "execution (* com. Zhw.service. *.*(..))" Represents the interception of ZHW under COM packets and sub-packages. Any of the classes under service packages and sub-packages--
<aop:pointcut id= "mypointcut" expression= "Execution (* com: Zhw.service. *.*(..))" />
<!--entry point for mypointcut, notification for Txadvice. -
<aop:advisor advice-ref= "Txadvice" pointcut-ref= "Mypointcut"/>
</aop:config>
Personally, the way XML is configured is a bit too rough, and it's a bit hard to handle when there are nested transactions (for lazy people like me).

2. Annotation statement

<!--enable annotation transaction management support in the XML configuration file--
<tx:annotation-driven/>
It has three properties

Transaction-manager: Specifies the transaction manager name, which defaults to TransactionManager

Proxy-target-class: Use the JDK dynamic agent by default for False,false, or use Cglibs proxy if true. The main difference between the settings for the JDK proxy and the Cglibs agent is that with the JDK proxy, @Transactional annotations can work on interfaces and classes and their methods, and cglibs can only be used on classes, and in order to avoid negligence, the recommendation is written on the class rather than on the interface, and Writes on the interface are not supported for inheritance.

Order: Defines the order of transaction notifications, by default giving the order discretion to AOP processing.

After opening the annotation transaction management in the configuration file, we can use the @transcational annotation for transaction management.

@Transcational
public class Superserviceimpl implements superservice{

public void Add ();

}


@Transactional
public class Subserviceimpl extends Superserviceimpl implements subservice{

public void update ();
}
These are the most common uses:

1, the @transactional annotation function on the class, by default, all methods of the class join the transaction

2, the @transactional annotation function on the parent class, it can be the quilt class integration.

@Transactional Note There are a number of custom properties that make his functionality richer.

Value: Specifies the transaction manager to support the multi-transaction manager environment

Isolation: Specify the transaction isolation level, default

readOnly: Whether the transaction is read-only, false by default. (That is, when the transaction begins, the data submitted by other firms is not visible to the transaction, and is often used in cases where multiple query statements are in the same transaction)

Timeout: Transaction time-out, in seconds. Default-1, which means that the timeout will depend on the underlying transaction system.

Rollbackfor: Specifies a set of exception classes that will be rolled back if not specified, and only the unchecked exception will be rolled back, and the checked exception is not rolled back.

Rollbackforclassname: the function ibid.

Norollbackfor: Specifies an exception class, and the transaction is not rolled back when the exception is encountered.

Norollbackforclassname: the function ibid.

Precautions:

1. @Transactional annotations can only be used on public methods, and other adornments will be ignored.

2. If @transactional annotations are specified on interfaces, classes, and methods, the priority is method--

3. It is recommended to add @transactional annotations on the class only, not on the interface.

4, the default only for unchecked exception rollback, the most common is runtimeexception and its various seed classes.

Then the basic use of spring business is the sauce:), visual inspection has been able to meet the needs of 80% or 90%.























Another article @transactional of inheriting classes

@Transactional This transaction annotation has no effect on the inherited method of the parent class.
Valid only for the current class and subclass, you can write @transactional on the parent class if you want to make it valid for the parent class method.
@transactional:org.hibernate.hibernateexception:no hibernate Session bound to thread of inheriting class, and configuration does not all ow creation of non-transactional one here

Suppose you have the following classes:

@Transactional
public class subclass extends superclass {


public void Loaddb () {
Database operations
}


}


public class Superclass {


public void Savedb () {
Database operations
}
}




Savedb is the method of the parent class, and Loaddb is the method of the subclass. If you have the following call:


@Test
public void Test () {
Subclass o = new Subclass ();
O.savedb ();//will report no session errors
O.LOADDB ();//Normal
}


You can see that the Hibernate report does not have a session error when you tune the parent class method (Org.hibernate.HibernateException:No hibernate session bound to thread, and Configuration does not allow creation of non-transactional one here), there is no problem with subclasses.


Workaround One: Overload the parent class method in the subclass:


@Transactional
public class subclass extends superclass {


public void Loaddb () {


}


@Override
public void Savedb () {
Super.savedb ();
}
}


This is obviously tedious, and the subclass Savedb does not have any new operations.


Workaround two: Label the @transactional in the parent class (the parent class is an abstract class, or you can):


@Transactional
public class Superclass {


public void Savedb () {


}


}


This requires the modification permission of the parent class.


---http://www.cnblogs.com/xiefeifeihu/archive/2010/07/27/1785958.html


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.