In-depth understanding of transaction--spring Annotated transaction configuration considerations

Source: Internet
Author: User
Tags aop config require requires rollback xmlns
1. Add @transactional annotations where transaction management is required.

@Transactional annotations can be applied to interface definitions and interface methods, class definitions, and public methods of classes. 2. @Transactional annotations can only be applied to methods of public visibility.

If you use @Transactional annotations on protected, private, or package-visible methods, it will not error, but this annotated method will not show the configured transaction settings. 3. Note that only @Transactional annotations appear to be less than open transaction behavior, which is simply a kind of meta data. The configuration element must be used in the configuration file to actually open the transaction behavior. See the configuration example at the bottom 4. Controls whether an interface-based or class-based proxy is created through the element's "Proxy-target-class" property value.

If the "Proxy-target-class" value is set to "true", then the class-based proxy will function (this requires the Cglib library Cglib.jar in classpath).

If the "Proxy-target-class" value is set to "false" or if this attribute is omitted, then the standard JDK interface-based proxy will work. such as
<!--standard JDK interface-based proxies will work-->
<tx:annotation-driven transaction-manager= "TransactionManager"   Proxy-target-class= "false"/>
<!--class-based proxies will work, while Cglib.jar must--> in Classpath;
<tx: Annotation-driven transaction-manager= "TransactionManager"  proxy-target-class= "true"/>


Non-JTA transactions (that is, non-distributed transactions), when a transaction is configured, the transaction manager (TransactionManager) needs to specify DataSource properties (non-distributed transactions, which are opened on links created by the database.

JTA transactions (distributed transactions), transaction managers (TransactionManager) cannot specify DataSource properties (distributed transactions, which have global transactions to manage database links)


Note @transactional Cglib and Java dynamic Agent The biggest difference is that the proxy target object does not implement the interface, then if the annotation is written to the interface method, if the use of Cglib proxy, this is the annotation thing is invalid, in order to maintain the compatibility of annotations is best written to the implementation class method.
5. The spring team recommends using @Transactional annotations on specific classes (or methods of classes) instead of using any interfaces that the class implements.

Using @Transactional annotations on an interface only takes effect if you set up an interface-based proxy. Because annotations are not inherited, this means that if a class-based proxy is being used, the transaction's settings will not be recognized by the class-based proxy, and the object will not be wrapped by the transaction proxy. 6. @Transactional transactions are opened, either interface-based or class-based proxies are created.

so in the same class one method calls another method with a transactional method, and the transaction does not work.

Public interface Personservice {
//delete the person with the specified ID, public
void Delete (Integer personid);
Delete person,flag public void Delete for the specified ID
(Integer personid,boolean flag)
;
public class Personservicebean implements Personservice {
private jdbctemplate jdbctemplate;


public void Delete (Integer PersonID) {
try{
this.delete (personid,true)
System.out.println ("delete Success ");
} catch (Exception e) {
System.out.println ("delete failed");
}
}
@Transactional
//At this point, the transaction is not turned on at all, that is, the database commits the operation by default, that is, the record does not delete the public void Delete (Integer Personid,boolean flag) {
if ( Flag = = ture) {
jdbctemplate.update ("Delete from person where id=?", New Object[]{personid},
new int[]{ Java.sql.Types.INTEGER});
throw new RuntimeException ("Run-time exception")
;
}}} public class personservicebeantest{
personservice PS = new Personservicebean ();
Ps.delete (5);
}


7. Spring uses declarative transactions, and by default all database operations are rollback if an unchecked exception occurs in the annotated database action method, or if the exception that occurs is a checked exception, the database operation is committed by default.
Public interface Personservice {//delete the person with the specified ID, public void Delete (Integer PersonID);//Get person public person Getperson
(Integer PersonID); }//personservicebean implements the Personservice interface, either interface-based or class-based proxies can implement transactions @Transactional public class Personservicebean


Implements Personservice {private JdbcTemplate jdbctemplate; A unchecked exception occurred, transaction rollback, @Transactional public void Delete (Integer PersonID) {jdbctemplate.update (' delete from '
Where id=? ", New Object[]{personid}, New Int[]{java.sql.types.integer});
throw new RuntimeException ("Run-time exception"); }
}
------------------------------------------------------------------------------------------------------------- --------------------------------------public interface Personservice {//delete the person with the specified ID, public void Delete (Integer
PersonID) throws Exception;
Gets the person public person Getperson (Integer PersonID); } @Transactional public class Personservicebean implements Personservice {//checked exception occurred, transaction does not rollback, database record can still be deleted,// The exception to checked requires that we call the method externally using Try/catch syntax.Place to include @Transactional public void Delete (Integer PersonID) throws exception{jdbctemplate.update ("Delete from person whe
Re id=? ", New Object[]{personid}, New Int[]{java.sql.types.integer});
throw new Exception ("Run-time exception"); }
}
------------------------------------------------------------------------------------------------------------- --------------------------------------However, the exception to checked is that it does not rollback a transaction by default, but if we need it for a transaction rollback,
You can modify its behavior by @transaction this annotation on the Delete method. @Transactional public class Personservicebean implements Personservice {@Transactional (rollbackfor=exception.class)/
/rollbackfor This property specifies that, even if you have an exception with checked, it also rolls back the transaction to public void Delete (Integer PersonID) throws exception{
Jdbctemplate.update ("Delete from person where id=?", New Object[]{personid}, New Int[]{java.sql.types.integer});
throw new Exception ("Run-time exception"); }
}



In Personservicebean this business bean, there are some transactions that do not require transaction management, such as the Getpersons method of acquiring data, Getperson method. Because the @transactional is placed above the class.

At this point, you can take the Propagation transaction property @transactional (propagation=propagation.not_supported),

Propagation This property specifies the transaction propagation behavior, we can specify that it does not support transactions, and when we write this, the spring container does not open the transaction until the Getpersons method executes.

@Transactional public
class Personservicebean implements Personservice {


@Transactional (propagation= propagation.not_supported)
//Then this method will not open the transaction the public person
Getperson (Integer PersonID)
{
}
}


####################################################### Mixed Transaction configuration instance:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns= "Http://www.springframework.org/schema/beans" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-2.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-2.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-2.0.xsd Http://www.springframework.org/schema/beans/HTTP Www.springframework.org/schema/beans/spring-beans.xsd "> <bean id=" DataSource "class=" Com.mchange.v2.c3p0.ComboPooledDataSource "destroy-method=" Close "> <property name=" driverclass "value=" ${ Db.driver} "></property> <property name=" Jdbcurl "value=" ${db.url} "></property> <property Name= "User"Value=" ${db.username} "></property> <property name=" password "value=" ${db.password} "></property > <property name= "acquireincrement" value= "2" ></property> <property name= "Preferredtestquery" Value= "Select 1 from Dual" ></property> <!--<property name= "Idleconnectiontestperiod" value= "Up" > </property> <property name= "initialpoolsize" value= "${db.minpoolsize}" ></property> < Property Name= "Minpoolsize" value= "${db.minpoolsize}" ></property> <property name= "Maxpoolsize" value= "$ {db.maxpoolsize} "></property> <property name=" MaxIdleTime "value=" ${db.maxidletime} "></property > </bean> <!--Transaction Manager: Non-JTA transactions (i.e. non-distributed transactions), the transaction manager (TransactionManager) needs to specify the DataSource attribute when the transaction is configured (non- Distributed transactions, transactions are opened on links created by the database. JTA Transaction (Distributed transaction), transaction manager (TransactionManager) cannot specify DataSource property (distributed transaction, there is global transaction to manage Database link)--<bean id= " TransactionManager "class=" Org.springframewoRk.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </ Bean> <!--define transactions using annotations annotation: If the "Proxy-target-class" value is set to "true",
	Then the class-based proxy will function (this requires the Cglib library Cglib.jar in classpath).

	If the "Proxy-target-class" value is set to "false" or if this attribute is omitted, then the standard JDK interface-based proxy will work. --<tx:annotation-driven transaction-manager= "TransactionManager" proxy-target-class= "true"/> <! --Use AOP transaction to define transactions--<tx:advice id= "Defaulttxadvice" transaction-manager= "TransactionManager" > <t x:attributes> <tx:method name= "get*" propagation= "REQUIRED" rollback-for= "Java.lang.Exception" isolation= " DEFAULT "/> <tx:method name=" query* "read-only=" true "/> <tx:method name=" search* "rea  D-only= "true"/> <tx:method name= "select*" read-only= "true"/> <tx:method name= "find*" Read-only= "true"/> <tx:method name= "insert*" propagation= "REQUIRED "rollback-for=" java.lang.Exception "isolation=" DEFAULT "/> <tx:method name=" save* "propagation=" REQ Uired "rollback-for=" java.lang.Exception "isolation=" DEFAULT "/> <tx:method name=" update* "propagation=" REQUIRED "rollback-for=" java.lang.Exception "isolation=" DEFAULT "/> <tx:method name=" delete* "Propagatio N= "REQUIRED" rollback-for= "java.lang.Exception" isolation= "DEFAULT"/> <tx:method name= "create*" Propaga tion= "REQUIRED" rollback-for= "java.lang.Exception" isolation= "DEFAULT"/> <tx:method name= "do*" Propagat ion= "REQUIRED" rollback-for= "java.lang.Exception" isolation= "DEFAULT"/> <tx:method name= "execute*" Propagatio N= "REQUIRED" rollback-for= "java.lang.Exception" isolation= "DEFAULT"/> <tx:method name= "*" read-only= "true" pro pagation= "REQUIRED" isolation= "DEFAULT"/> </tx:attributes> </tx:advice> <tx:advice id= "Logtxadvic E "transaction-manager=" tRansactionmanager "> <tx:attributes> <tx:method name=" get* "propagation=" REQUIRED "Rol
            Lback-for= "Java.lang.Exception" isolation= "DEFAULT"/> <tx:method name= "query*" read-only= "true"/> <tx:method name= "search*" read-only= "true"/> <tx:method name= "select*" read-only= "true"/ > <tx:method name= "find*" read-only= "true"/> <tx:method name= "*" propagation= "REQUIRE S_new "rollback-for=" java.lang.Exception "/> </tx:attributes> </tx:advice& 
	Gt
		<!--the "order" parameter, which is used to control the precedence of an AOP notification, the smaller the value, the higher the priority, and the parameter to be set when the hybrid transaction is configured. Execution: Use the Execution (method expression) matching method to perform within: use within (type expression) to match methods within a specified type--<aop:config> &LT;AOP:POINTC UT id= "defaultoperation" expression= "Execution (* *). *serviceimpl.* (..)) " /> <aop:pointcut id= "logserviceoperation" expression= "@within (com.homent.service. Logservice+ "/> <aop:advisor advice-ref=" Defaulttxadvice "order=" 3 "pointcut-ref=" DefaultO  
	Peration "/> <aop:advisor advice-ref=" Logtxadvice "order=" 2 "pointcut-ref=" Logserviceoperation "/> </aop:config> </beans>



Reference post: http://blog.sina.com.cn/s/blog_667ac0360102ebem.html

Spring's AOP aspectj pointcut syntax: http://jinnianshilongnian.iteye.com/blog/1415606


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.