Generation  pregnant  who C Spring AOP transaction management scenarios of

Generation  pregnant  who C█ Micro Signal █: 138 • 0226 • 9370█ █ successful surrogacy package bag pack healthy sex surrogate █ ██ bag boy

Spring AOP transaction management scenarios of

1, when the transaction is executed in front of the open transaction, behind closed transaction, the transaction ends, there are two ways, one is normal to commit the transaction, one is the problem roll back the transaction occurs.

Only in the spring Affairs default will throw an unchecked Exception rollback

UncheckedException include all subclasses of the derived error and runtimeException

2, what matters when it is used?
When a batch of data in the database table or even operation, in order to ensure consistency and accuracy of the data, we need to add transaction management mechanism to manage. When data in the database fails to operate, transaction management can guarantee a good roll back all the data to the original data, if the operation is successful, needs to be updated to ensure that all data persistence.

For example: 1 transfer:. A transfer to B, A's need to put money to lose money then B plus, any one of these two operations fail, we must withdraw the entire transfer process, otherwise it will be a big problem.

2. Insert the orders to the database, and then insert the first insertion order line items, these two operations will affect the consistency of any data fails, it is necessary to make the transaction process

3, Spring transaction configuration of
   declarative transaction (no need to open the annotation proxy, etc.)

   To configure notifications (explain what methods need to intercept method intercepted apply the configured transaction attributes)

   Configuring an entry point to the need for transaction management which class

Note: Some of those methods will notify management

A. Spring support programmatic transaction management and declarative transaction management in two ways

 

  Programmatic transaction management using TransactionTemplate or directly use the underlying PlatformTransactionManager. For programmatic transaction management, spring recommended TransactionTemplate.

 

      Declarative transaction management built on AOP. Its essence is to intercept method before and after, and then create or join a transaction before the target method begins, commit or roll back the transaction in accordance with the implementation after executing the target method. The biggest advantage is declarative transaction does not need to programmatically manage transactions, transaction management so you do not need doping code in the business logic code, just do the relevant business rules declared in the configuration file (or by @Transactional based notes the way), you can apply the rule to the transaction of business logic.

 

       Declarative transaction management is clearly superior to programmatic transaction management, which is the spring non-invasive way of development advocated. Declarative transaction management to make business code from pollution, a common POJO objects, as long as annotate can get full transaction support. And programmatic transaction compared declarative transaction where only downside is that the latter can only be applied to most fine-grained method level, you can not do as programmatic transaction that can be applied to the block level. But even if there is such a demand, there are many alternative methods, for example, can require transaction management code block is independent method and so on.

 

        Declarative transaction management, there are two common ways, one is based on xml configuration file tx and aop namespace, while another is based on @Transactional comments. Obviously annotation-based method is more simple to use, more refreshing. But personal recommendation Profiles with xml.

Two. Spring transactional properties

spring all transaction management strategy classes inherit from org.springframework.transaction.PlatformTransactionManager Interface

Wherein TransactionDefinition interface defines the following features:

1. The transaction isolation level

  Isolation level refers to the degree of isolation between the number of concurrent transactions. TransactionDefinition interface defines five levels of isolation represent constants:

  TransactionDefinition.ISOLATION_DEFAULT: This is the default, use the default isolation level of the underlying database. For most databases, usually this value is TransactionDefinition.ISOLATION_READ_COMMITTED.
  TransactionDefinition.ISOLATION_READ_UNCOMMITTED: This represents a transaction isolation level data can be read another transaction modified but not yet committed. This level can not prevent dirty reads, non-repeatable read and phantom read, the isolation level is rarely used. For example, PostgreSQL actually does not have this level.
  TransactionDefinition.ISOLATION_READ_COMMITTED: The isolation level represents a transaction can only read data another transaction has been submitted. This level prevents dirty reads, which is the recommended value in most cases.
  TransactionDefinition.ISOLATION_REPEATABLE_READ: The isolation level indicates that a transaction can execute a query repeatedly throughout the process, and each returned record are the same. The levels prevent dirty reads and non-repeatable read.
  TransactionDefinition.ISOLATION_SERIALIZABLE: All transactions executed one by one in sequence, it is impossible to produce interference between such matters, that is to say, this level prevents dirty reads, non-repeatable reads and phantom reads. But this will seriously affect the performance of the program. Under normal circumstances you do not need this level.

2. The transaction propagation behavior

      The so-called spread behavior of affairs means that if before the start of the current transaction, a transaction context already exists, then there are several options you can specify execution behavior of a transactional approach. Comprising the following several represents the propagation constant in the behavior definition TransactionDefinition:

  TransactionDefinition.PROPAGATION_REQUIRED: If the current transaction exists, it is added to the transaction; if no transaction, create a new business. It's the default value.
  TransactionDefinition.PROPAGATION_REQUIRES_NEW: create a new transaction, if the current transaction exists, put the current transaction pending.
  TransactionDefinition.PROPAGATION_SUPPORTS: If the current transaction exists, it is added to the transaction; if no transaction, non-transactional way places continue to run.
  TransactionDefinition.PROPAGATION_NOT_SUPPORTED: non-transaction run, if the current transaction exists, put the current transaction pending.
  TransactionDefinition.PROPAGATION_NEVER: non-transaction run, if the current transaction exists, an exception is thrown.
  TransactionDefinition.PROPAGATION_MANDATORY: If the current transaction exists, it is added to the transaction; if no transaction, an exception is thrown.

  TransactionDefinition.PROPAGATION_NESTED: If the current transaction exists, create a transaction to run as the current nested transaction transaction; if no transaction, the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.

3. Transaction Timeout

      The so-called transaction timeout, a firm refers to the maximum time allowed to perform, if it exceeds the time limit but the transaction has not been completed, it automatically rolls back the transaction. In TransactionDefinition a value represented int timeout, which in seconds.

  The default setting for the timeout value of the underlying transaction system, if the underlying database transaction system is not set timeout values, then that is none, no timeout limit.

4. Transaction read-only attribute

      Read-only transaction for the customer code read-only, but the situation does not modify the data, optimized for read-only transactions under certain scenarios, such as when using Hibernate.
The default is read and write transactions.

        "Read-only transaction" is not a mandatory option, it's just a "hint", suggesting that the database drivers and database systems, this transaction does not include changes to the operation of the data, then the JDBC driver and database according to this situation is likely to the transaction some specific optimizations, for example, to say no to arrange the appropriate database lock, to relieve the pressure on the database of the transaction, after the transaction is to consume resources database. 

But you have to modify the "read-only transaction" inside data, it is not impossible, but for consistency of data protection is not as insurance "read and write transactions" only. 

Therefore, the "read-only transaction" is simply a performance optimization recommended configuration only, not mandatory that you do not

5.spring transaction rollback rules

     Indicating spring transaction manager to roll back a transaction recommended method is to throw an exception in the context of the current transaction. spring Transaction Manager will catch any unhandled exceptions, and then decide whether to roll back the transaction throws an exception basis rules.

        The default configuration, spring is only an exception thrown when the transaction is rolled back to unchecked runtime exceptions, an exception is thrown into a subclass of RuntimeException (Errors will cause a rollback), and then throw checked exceptions It will not cause a rollback. The configuration can be thrown clear when those exceptions roll back the transaction, including checked exceptions. You can also explicitly define those not roll back the transaction when an exception is thrown. Can also be programmed by setRollbackOnly () method to indicate that a transaction must roll back, the only action is to rollback After calling setRollbackOnly () you can perform.

III. Configuring Declarative transaction based on xml files

(1) Configuration Management Services

 

Configuration data source (the dataSource) in the spring configuration, transaction manager, the transaction manager uses a different frame orm transaction manager is based on various mybatis org.springframework.jdbc.datasource.DataSourceTransactionManager. The hibernate transaction manager is org.springframework.orm.hibernate3.HibernateTransactionManager.

(2) Configure transaction properties

Transaction properties: for <tx method> set, Spring supports a different set of attributes different transaction methods, it may be one of: a plurality of <tx advice> <tx: method>, where the name attribute specifies the matching method ( it should be naming conventions for these methods, if the transaction entry point in the service, and the best way to Dao distinguished name, and do not use keywords get set, getter setter properties and prevent confusion)

Transaction has the following common attributes:

a.read-only: setting whether to allow the transaction to modify the data. (Only for transactions executed query function, set to TRUE can improve the execution speed of the transaction)  

b.propagation: propagation mechanisms affairs. Generally set required. Ensure that the code can only run in a transaction in the current transaction, prevent the creation of multiple transactions.

c.isolation: transaction isolation level. It is not necessary. The default value is the default.

d.timeout: the maximum time allowed to run the transaction, in seconds.

e.rollback-for: trigger a rollback exception.

f.no-rollback-for: will not trigger a rollback exception.

*** actual development, transaction execution only for query function, to set read-only is TRUE, other properties generally use the default value.

(3) Configuration affairs AOP entry point

该设置的含义是:对于org.sl.netmarket.services包及子包下的所有类的所有公共方法进行切入。(被切入的 方法经过<tx:method>筛选)web应用程序最合适的事务切入点是Service的方法上。

     通过以上三个步骤设置好声明式事务后,当Service中 的业务方法被调用之前,Spring会获取事务对象并启动事务。并使用try-catch-finally来处理异常。业务方法执行成功则会提交事务,默认情况下如果抛出了RuntimeException 或者Rrror 对象就会回滚事务。(注意: 这里注意一下,在tx:method中配置了rollback_for 中配置的Exception 这个是运行时的异常才会回滚不然其他异常是不会回滚的!)

这里示例一下:

1、数据访问接口:

我这里定义了多个,我只示例一个就可以了。

2、dao接口的mapper映射文件:manager_mapper.xml

 

3、业务逻辑接口:

4、业务逻辑实现

5、mybatis 核心配置文件:netmk_mybatis_conf.xml

 

7、配置项目(重点)

spring核心配置文件:netmk_spring_config.xml

 

8、测试:

9、结果

也存到了数据库中了的

四.  基于注解文件配置声明式事务

1.在事务管理的dao实现类之前标注@Transactional

2.在要进行事务管理的方法前加上如@Transactional(propagation= Propagation.REQUIRED)

3.在配置文件中指定驱动:<tx:annotation-driven transaction-manager="transactionManager" />

示例:

@Transactional属性 

 

用法

       @Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。

        虽然 @Transactional 注解可以作用于接口、接口方法、类以及类方法上,但是 Spring 建议不要在接口或者接口方法上使用该注解,因为这只有在使用基于接口的代理时它才会生效。另外, @Transactional 注解应该只被应用到 public 方法上,这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 @Transactional 注解,这将被忽略,也不会抛出任何异常。

        默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使用@Transactional注解进行修饰。

1、事务执行的时候是在前面开启事务,后面关闭事务,结束事务有两种方式,一种是正常的提交事务,一种是出现问题回滚事务。

spring事务默认只有在抛出unchecked Exception才会回滚

UncheckedException包括error和runtimeException派生出的所有子类

2、什么时候才用事务?
对数据库的数据进行批量或连表操作时,为了保证数据的一致性和正确性,我们需要添加事务管理机制进行管理。当对数据库的数据进行操作失败时,事务管理可以很好保证所有的数据回滚到原来的数据,如果操作成功,则保证所有需要更新的数据持久化。

例如:1.转账:A对B转账,需要先把A的钱减掉再把B的钱加上,这两个操作任何一个失败,都要撤销整个转账过程,不然会出大问题。

2.向数据库中插入订单时,先插入订单再插入订单项,这两个操作任何一个失败都会影响数据的一致性,所以必须做事务的处理

3、Spring事务的配置
   声明式事务(不需要开启注解代理等等)

   配置通知(说明哪些方法需要拦截,被拦截的方法将应用配置好的事务属性)

   配置切入点需要对哪个类进行事务管理

注意:只会管理通知中有的那些方法

一.  Spring支持编程式事务管理和声明式事务管理两种方式

 

  编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager。对于编程式事务管理,spring推荐使用TransactionTemplate。

 

      声明式事务管理建立在AOP之上的。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务最大的优点就是不需要通过编程的方式管理事务,这样就不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式),便可以将事务规则应用到业务逻辑中。

 

       显然声明式事务管理要优于编程式事务管理,这正是spring倡导的非侵入式的开发方式。声明式事务管理使业务代码不受污染,一个普通的POJO对象,只要加上注解就可以获得完全的事务支持。和编程式事务相比,声明式事务唯一不足地方是,后者的最细粒度只能作用到方法级别,无法做到像编程式事务那样可以作用到代码块级别。但是即便有这样的需求,也存在很多变通的方法,比如,可以将需要进行事务管理的代码块独立为方法等等。

 

        声明式事务管理也有两种常用的方式,一种是基于tx和aop名字空间的xml配置文件,另一种就是基于@Transactional注解。显然基于注解的方式更简单易用,更清爽。但是个人推荐用xml配置文件的方式。

二.  Spring事务特性

spring所有的事务管理策略类都继承自org.springframework.transaction.PlatformTransactionManager接口

其中TransactionDefinition接口定义以下特性:

1.事务隔离级别

  隔离级别是指若干个并发的事务之间的隔离程度。TransactionDefinition 接口中定义了五个表示隔离级别的常量:

  TransactionDefinition.ISOLATION_DEFAULT:这是默认值,表示使用底层数据库的默认隔离级别。对大部分数据库而言,通常这值就是TransactionDefinition.ISOLATION_READ_COMMITTED。
  TransactionDefinition.ISOLATION_READ_UNCOMMITTED:该隔离级别表示一个事务可以读取另一个事务修改但还没有提交的数据。该级别不能防止脏读,不可重复读和幻读,因此很少使用该隔离级别。比如PostgreSQL实际上并没有此级别。
  TransactionDefinition.ISOLATION_READ_COMMITTED:该隔离级别表示一个事务只能读取另一个事务已经提交的数据。该级别可以防止脏读,这也是大多数情况下的推荐值。
  TransactionDefinition.ISOLATION_REPEATABLE_READ:该隔离级别表示一个事务在整个过程中可以多次重复执行某个查询,并且每次返回的记录都相同。该级别可以防止脏读和不可重复读。
  TransactionDefinition.ISOLATION_SERIALIZABLE:所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,也就是说,该级别可以防止脏读、不可重复读以及幻读。但是这将严重影响程序的性能。通常情况下也不会用到该级别。

2.事务传播行为

      所谓事务的传播行为是指,如果在开始当前事务之前,一个事务上下文已经存在,此时有若干选项可以指定一个事务性方法的执行行为。在TransactionDefinition定义中包括了如下几个表示传播行为的常量:

  TransactionDefinition.PROPAGATION_REQUIRED:如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。这是默认值。
  TransactionDefinition.PROPAGATION_REQUIRES_NEW:创建一个新的事务,如果当前存在事务,则把当前事务挂起。
  TransactionDefinition.PROPAGATION_SUPPORTS:如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行。
  TransactionDefinition.PROPAGATION_NOT_SUPPORTED:以非事务方式运行,如果当前存在事务,则把当前事务挂起。
  TransactionDefinition.PROPAGATION_NEVER:以非事务方式运行,如果当前存在事务,则抛出异常。
  TransactionDefinition.PROPAGATION_MANDATORY:如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常。

  TransactionDefinition.PROPAGATION_NESTED:如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。

3.事务超时

      所谓事务超时,就是指一个事务所允许执行的最长时间,如果超过该时间限制但事务还没有完成,则自动回滚事务。在 TransactionDefinition 中以 int 的值来表示超时时间,其单位是秒。

  默认设置为底层事务系统的超时值,如果底层数据库事务系统没有设置超时值,那么就是none,没有超时限制。

4.事务只读属性

      只读事务用于客户代码只读但不修改数据的情形,只读事务用于特定情景下的优化,比如使用Hibernate的时候。
默认为读写事务。

        “只读事务”并不是一个强制选项,它只是一个“暗示”,提示数据库驱动程序和数据库系统,这个事务并不包含更改数据的操作,那么JDBC驱动程序和数据库就有可能根据这种情况对该事务进行一些特定的优化,比方说不安排相应的数据库锁,以减轻事务对数据库的压力,毕竟事务也是要消耗数据库的资源的。 

但是你非要在“只读事务”里面修改数据,也并非不可以,只不过对于数据一致性的保护不像“读写事务”那样保险而已。 

因此,“只读事务”仅仅是一个性能优化的推荐配置而已,并非强制你要这样做不可

5.spring事务回滚规则

     指示spring事务管理器回滚一个事务的推荐方法是在当前事务的上下文内抛出异常。spring事务管理器会捕捉任何未处理的异常,然后依据规则决定是否回滚抛出异常的事务。

        默认配置下,spring只有在抛出的异常为运行时unchecked异常时才回滚该事务,也就是抛出的异常为RuntimeException的子类(Errors也会导致事务回滚),而抛出checked异常则不会导致事务回滚。可以明确的配置在抛出那些异常时回滚事务,包括checked异常。也可以明确定义那些异常抛出时不回滚事务。还可以编程性的通过setRollbackOnly()方法来指示一个事务必须回滚,在调用完setRollbackOnly()后你所能执行的唯一操作就是回滚。

三.  基于xml文件配置声明式事务

(1)配置事务管理类

 

在spring的配置中配置数据源(dataSource)、事务管理器,事务管理器使用不同的orm框架事务管理器类就不同mybatis是org.springframework.jdbc.datasource.DataSourceTransactionManager。而hibernate事务管理器为org.springframework.orm.hibernate3.HibernateTransactionManager  。

(2)配置事务属性

事务属性在<tx:method>中进行设置,Spring支持对不同的方法设置不同的事务属性,所以可以为一个<tx:advice>设置多个<tx:method>,其中name属性指定匹配的方法(这里需要对这些方法名进行约定,如果事务切入点在service上,则最好和Dao的方法命名区分开,也不要使用get set关键字,防止和属性的getter setter发生混淆)

事务有以下几个常用属性:

a.read-only:设置该事务中是否允许修改数据。(对于只执行查询功能的事务,设置为TRUE可以提高事务的执行速度)  

b.propagation:事务的传播机制。一般设置为required。可以保证在事务中的代码只在当前事务中运行,防止创建多个事务。

c.isolation:事务隔离级别。不是必须的。默认值是default。

d.timeout:允许事务运行的最长时间,以秒为单位。

e.rollback-for:触发回滚的异常。

f.no-rollback-for:不会触发回滚的异常。

***实际开发中,对于只执行查询功能的事务,要设置read-only为TRUE,其他属性一般使用默认值即可。

(3)配置事务的AOP切入点

该设置的含义是:对于org.sl.netmarket.services包及子包下的所有类的所有公共方法进行切入。(被切入的 方法经过<tx:method>筛选)web应用程序最合适的事务切入点是Service的方法上。

     通过以上三个步骤设置好声明式事务后,当Service中 的业务方法被调用之前,Spring会获取事务对象并启动事务。并使用try-catch-finally来处理异常。业务方法执行成功则会提交事务,默认情况下如果抛出了RuntimeException 或者Rrror 对象就会回滚事务。(注意: 这里注意一下,在tx:method中配置了rollback_for 中配置的Exception 这个是运行时的异常才会回滚不然其他异常是不会回滚的!)

这里示例一下:

1、数据访问接口:

我这里定义了多个,我只示例一个就可以了。

2、dao接口的mapper映射文件:manager_mapper.xml

 

3、业务逻辑接口:

4、业务逻辑实现

5、mybatis 核心配置文件:netmk_mybatis_conf.xml

 

7、配置项目(重点)

spring核心配置文件:netmk_spring_config.xml

 

8、测试:

9、结果

也存到了数据库中了的

四.  基于注解文件配置声明式事务

1.在事务管理的dao实现类之前标注@Transactional

2.在要进行事务管理的方法前加上如@Transactional(propagation= Propagation.REQUIRED)

3.在配置文件中指定驱动:<tx:annotation-driven transaction-manager="transactionManager" />

示例:

@Transactional属性 

 

用法

       @Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。

        虽然 @Transactional 注解可以作用于接口、接口方法、类以及类方法上,但是 Spring 建议不要在接口或者接口方法上使用该注解,因为这只有在使用基于接口的代理时它才会生效。另外, @Transactional 注解应该只被应用到 public 方法上,这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 @Transactional 注解,这将被忽略,也不会抛出任何异常。

        默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使用@Transactional注解进行修饰。

Guess you like

Origin www.cnblogs.com/DENG012/p/10948016.html