spring, mybatis transaction management and configuration @Transactional annotation using [rpm]

Original link: https://www.cnblogs.com/xusir/p/3650522.html

转自https://www.cnblogs.com/xusir/p/3650522.html

spring, mybatis transaction management configuration and annotation using @Transactional

Overview of
transaction management for enterprise applications is critical, even if there is an abnormal situation, it can also ensure data consistency.
Spring Framework's transaction management provides a consistent abstraction, which is characterized as follows:

Provide different transaction API consistent programming model, such as JTA (Java Transaction API), JDBC , Hibernate, JPA (Java Persistence API and JDO (Java Data Objects)
support for declarative transaction management, in particular based on the annotation of declarative transaction management easy to use
provides a simpler API than other transactions, such as JTA transaction management API programming
and data access abstraction of a perfect spring integrated
transaction management

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.

Submit it automatically when the auto-commit (AutoCommit) and the connection is closed

Auto Commit

By default, the database is in auto-commit mode. Each statement in a separate transaction, when this statement is finished, if executed successfully implicit commit the transaction, if
fails the implicit transaction is rolled back.

For normal transaction management, it is in a group of related operations in a transaction, it is necessary to turn off auto-commit mode database. However, we do not have to worry about this, automatically submit attribute to false spring will be the underlying connection.
org / springframework / jdbc / datasource / DataSourceTransactionManager.java

// switch to manual commit if necessary. this is very expensive in some jdbc drivers,
// so we don't want to do it unnecessarily (for example if we've explicitly
// configured the connection pool to set it already).
if (con.getautocommit()) {
    txobject.setmustrestoreautocommit(true);
    if (logger.isdebugenabled()) {
        logger.debug("switching jdbc connection [" + con + "] to manual commit");
    }
    con.setautocommit(false);
}

Some of the data is provided to close the connection pool provides automatic transaction submitted, preferably in the connection pool when it is turned off. C3P0 but did not provide this feature, you can only rely on spring set.
Because the JDBC specification, when the connection object should establish in auto-commit mode, which is the default cross-DBMS, if necessary, must explicitly turn off the automatic submission. C3P0 comply with the code, so that the client code to explicitly set the desired mode of submission.

Submit it automatically when the connection is closed

When a connection is closed, if there is an uncommitted transaction should we do? JDBC specification does not mention, C3P0 default strategy is to roll back any uncommitted transactions. This is the right strategy, but this issue between the JDBC driver provider does not agree.
C3P0 of autoCommitOnClose property default is false, there is no essential not to touch it. Or you can explicitly set this property to false, it will be more clear.

Annotation-based declarative transaction management configuration
spring-servlet.xml

<!-- transaction support-->
<!-- PlatformTransactionMnager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<!-- enable transaction annotation support -->
<tx:annotation-driven transaction-manager="txManager" />

Also add tx namespace in the spring-servlet.xml

...
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
    ...
 
http://www.springframework.org/schema/tx
 
 
http://www.springframework.org/schema/tx/spring-tx.xsd
 
    ...

MyBatis to participate in spring automatic transaction management, without additional configuration, the same as long as org.mybatis.spring.SqlSessionFactoryBean referenced data sources and DataSourceTransactionManager referenced data sources, or transaction management will not work.

Further dependencies need to download aopalliance.jar is placed under the WEB-INF / lib directory. Otherwise, an exception will be reported when the spring is initialized
java.lang.NoClassDefFoundError: org / aopalliance / intercept / MethodInterceptor

spring characteristics Affairs

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

public interface PlatformTransactionManager {
 
  TransactionStatus getTransaction(TransactionDefinition definition)
    throws TransactionException;
 
  void commit(TransactionStatus status) throws TransactionException;
 
  void rollback(TransactionStatus status) throws TransactionException;
}

Wherein TransactionDefinition interface defines the following features:

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.
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. This is 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.
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.

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.

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.

@Transactional comment

@Transactional property

Attributes Types of description
value String Alternatively defined descriptors specify the transaction manager
propagation enum: Propagation The optional transaction propagation behavior settings
isolation enum: Isolation The optional transaction isolation level
readOnly boolean Read-write or read-only transaction, the default read and write
timeout int (in seconds granularity) Transaction timeout
rollbackFor Array of Class objects, must be inherited from Throwable Resulting in abnormal class array of transaction rollback
rollbackForClassName An array of class names, must be derived from Throwable Cause a rollback exception class names array
noRollbackFor Array of Class objects, must be inherited from Throwable It will not cause an exception class array of transaction rollback
noRollbackForClassName An array of class names, must be derived from Throwable It will not cause a rollback exception class names array

usage

@Transactional can be applied to the interface, the interface methods, classes, and class method. When used as a class, all the public methods of the class will have this type of transaction attributes, and we can also use this annotation at the method level to cover class level definition.

Although @Transactional annotation can be applied to the interface, the interface methods, classes and class methods, but Spring is not recommended to use the annotations on interface or an interface method, because it is only used when the agent interface based on it to take effect. In addition, @Transactional annotation should only be applied to public method, which is determined by the nature of the Spring AOP. If you're protected, private or default on the method of use @Transactional annotation visibility, it will be ignored, and no exception is thrown.

By default, only the method from outside the caller will be captured AOP proxy, that is, within the class method calls other methods of this class does not cause internal affairs of behavior, even if the method is called annotation @Transactional modified.

@Transactional(readOnly = true)
public class DefaultFooService implements FooService {
 
  public Foo getFoo(String fooName) {
    // do something
  }
 
  // these settings have precedence for this method
  //方法上注解属性会覆盖类注解上的相同属性
  @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
  public void updateFoo(Foo foo) {
    // do something
  }
}

Guess you like

Origin blog.csdn.net/weixin_44510465/article/details/102461854