Configuring and using Spring transactions

Spring's transaction support

Spring provides two transaction management, divided into programmatic and declarative.

  • 编程式: Enables manually coded way, commit or roll back the transaction, more granular, but more trouble.
  • 声明式: By adding annotation on packaging methods or a class or interface, transaction achieve non-invasive manner, more convenient, but larger particle size.

It should be noted that the use of the database required to support the transaction, otherwise the transaction will not work. MySql as the MyIsam engine does not support transactions.

Spring transaction configuration

Add dependent

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-tx</artifactId>
		<version>${spring.version}</version>
	</dependency>
复制代码

Configuring Transaction Manager

	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<!-- 如果使用基于注解的声明式事务,需要配置annotation-driven -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
复制代码

Obviously, transactionManager the transaction should be dataSource operation code dataSource, or how to manage it.

With programmatic transaction of

Began in the code, commit or roll back the transaction:

	// 开始事务
	TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
	// 异常回滚,并不一定要在try...catch中
	transactionManager.rollback(status);
	// 提交事务
	transactionManager.commit(status);
复制代码

Generally, the appropriate method of use:

	TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
	try {
		// 进行需要处在同一事务中的数据库操作
		......
		// 正常结束,提交事务
		transactionManager.commit(status);
	} catch (SomeException) {
		// 错误处理
		......
		// 回滚
		transactionManager.rollback(status);
	}
复制代码

Use declarative transactions

Directly in or added to the class method @Transactionnotes to:

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public int save(Info info) throws Exception {
复制代码

@TransactionNotes the common parameters:

propagation propagation behavior

  • REQUIRED(默认值)It must be run in the context of a transaction having: if no (outer layer) transaction, creates a new transaction; currently exists (outer layer) transaction, then added to the current (outer layer) transaction. (If the called method exception occurs, then call the method and the method being invoked transactions are rolled back) This is the most common choice.
  • SUPPORTS Support current (outer layer) transaction, if no (outer layer) transaction is executed in a non-transactional way.
  • MANDATORY Forced to use the current (outer layer) transaction, if no (outer layer) transaction, throw an exception.
  • REQUIRES_NEW Create a new transaction, and run in the transaction, currently exists (outer layer) transaction, the first current (outer layer) transaction suspension
  • NOT_SUPPORTED Performing an operation to a non-transactional manner: currently exists (outer layer) transaction, leave the current (outer layer) pending transaction.
  • NEVER To perform non-transactional way: If you currently exists (outer layer) transactions, an exception is thrown.
  • NESTED Performed in a nested manner: currently exists (outer layer) transaction, nested run independently places its own transaction, without affecting the current (outer layer) transaction, and the current (outer layer), if a transaction rolls back, then the transaction must be rolled back; if not currently exist (outer layer) transaction, with PROPAGATION.REQUIRED similar operation is performed.

isolation isolation level

  • DEFAULT Use the default database transaction isolation level
  • READ_UNCOMMITTED Modify allowed to read yet, and may result in dirty reads, phantom reads and non-repeatable read
  • READ_COMMITTED Allowed to read from the transaction has been submitted, prevents dirty reads, but phantom reads, non-repeatable reads are still possible
  • REPEATABLE_READThe results of multiple reads of the same field is the same, unless the data is modified current transaction itself. Prevents dirty reads and non-repeatable reads, but phantom reads still occur
  • SERIALIZABLE ACID completely obey the principle of isolation, to ensure that does not happen dirty reads, non-repeatable reads, and phantom reads, but the lowest efficiency.

Are readOnly read-only transaction

It indicates whether the transaction is read only data but data is not updated, only the read transaction is set to read-only operations can help to optimize transactional database engine.

timeout timeout

Avoid locking the database for a long time, in seconds.

rollbackFor rollback exception class

By default only the runtime exception rollback, see below.

Defects declarative transactions

Internal class calls

Spring's declarative transaction by way of dynamic AOP proxy, it will produce a realization of the transaction proxy class, the distinction between the original class. Consider a situation:

  • Service methods in the class A does not declare Affairs
  • Service Method B Statement of Affairs
  • Method A Method B calls the internal

In this case, call the Service of method B, using a proxy class Service 'method B, is to achieve a method of transaction, rollback exception occurs.

But if the call is method A, used in the interior of the original proxy class Service class method B, does not implement the transaction will not lead to abnormal rollback.

Solution : B split method to another class, the method is guaranteed to be called the proxy class instead of the original class.

Wrong use

Declarative transaction packaging methods will be rolled back when the method throws an exception, but only by default throws RuntimeExceptionrollback.

If an exception is catch live eaten or thrown out non RuntimeException, then the default is not rolled back.

Solution : Do not swallow exceptions, encountered non- RuntimeExceptionuse @Transactionannotation rollbackForparameters are controlled.

Java8 in java.lang part of the class hierarchy is as follows (please see the complete structure of the bottom of the article references):

java.lang.Object
	......
	java.lang.Throwable (implements java.io.Serializable)
		java.lang.Error
			java.lang.AssertionError
			java.lang.LinkageError
				java.lang.BootstrapMethodError
				java.lang.ClassCircularityError
				java.lang.ClassFormatError
					java.lang.UnsupportedClassVersionError
				java.lang.ExceptionInInitializerError
				java.lang.IncompatibleClassChangeError
					java.lang.AbstractMethodError
					java.lang.IllegalAccessError
					java.lang.InstantiationError
					java.lang.NoSuchFieldError
					java.lang.NoSuchMethodError
				java.lang.NoClassDefFoundError
				java.lang.UnsatisfiedLinkError
				java.lang.VerifyError
			java.lang.ThreadDeath
			java.lang.VirtualMachineError
				java.lang.InternalError
				java.lang.OutOfMemoryError
				java.lang.StackOverflowError
				java.lang.UnknownError
		java.lang.Exception
			java.lang.CloneNotSupportedException
			java.lang.InterruptedException
			java.lang.ReflectiveOperationException
				java.lang.ClassNotFoundException
				java.lang.IllegalAccessException
				java.lang.InstantiationException
				java.lang.NoSuchFieldException
				java.lang.NoSuchMethodException
			// 这里是RuntimeException
			java.lang.RuntimeException
				java.lang.ArithmeticException
				java.lang.ArrayStoreException
				java.lang.ClassCastException
				java.lang.EnumConstantNotPresentException
				java.lang.IllegalArgumentException
					java.lang.IllegalThreadStateException
					java.lang.NumberFormatException
				java.lang.IllegalMonitorStateException
				java.lang.IllegalStateException
				java.lang.IndexOutOfBoundsException
					java.lang.ArrayIndexOutOfBoundsException
					java.lang.StringIndexOutOfBoundsException
				java.lang.NegativeArraySizeException
				java.lang.NullPointerException
				java.lang.SecurityException
				java.lang.TypeNotPresentException
				java.lang.UnsupportedOperationException
	......
复制代码

Reference material

Spring declarative transaction - Jane books

In the spring of the same declarative transaction method invocation transaction failure - Yunqi Community - Ali cloud (. Ps this is not the original, I really could not find the original text)

java.lang Class Hierarchy (Java Platform SE 8 )

This article moved from my blog , welcome to visit!

Guess you like

Origin juejin.im/post/5d380bf2e51d454f73356e22