Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a transaction in spring

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly talks about "what is the business in spring". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the business in spring"?

1) transaction manager of spring:

Package org.springframework.transaction;public interface PlatformTransactionManager {TransactionStatus getTransaction (TransactionDefinition definition) throws TransactionException; void commit (TransactionStatus status) throws TransactionException; void rollback (TransactionStatus status) throws TransactionException;}

2) transaction definition class of spring:

The propagation behavior of the package org.springframework.transaction;import java.sql.Connection;public interface TransactionDefinition {/ / transaction int PROPAGATION_REQUIRED = 0; / / join the transaction if it currently exists, or create a new transaction if there is no transaction currently. This is the default value. Int PROPAGATION_SUPPORTS = 1; / / if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner. Int PROPAGATION_MANDATORY = 2; / / join a transaction if there is currently a transaction, or throw an exception if there is no transaction. Int PROPAGATION_REQUIRES_NEW = 3; / / create a new transaction and suspend the current transaction if it exists. Int PROPAGATION_NOT_SUPPORTED = 4; / / runs in a non-transactional manner, suspending the current transaction if there is a current transaction. Int PROPAGATION_NEVER = 5; / / runs in a non-transactional manner, and throws an exception if a transaction currently exists. Int PROPAGATION_NESTED = 6; / / if there is a transaction, a transaction is created to run as a nested transaction of the current transaction; if there is no transaction, it is equivalent to PROPAGATION_REQUIRED. / / the isolation level of the transaction int ISOLATION_DEFAULT =-1; / / use the default isolation level of the underlying database. Int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED; int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED; int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ; int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE; / * * Use the default timeout of the underlying transaction system, or none if timeouts are not supported. * / / transaction timeout: the maximum time a transaction is allowed to execute. If the time limit is exceeded but the transaction has not been completed, the transaction is automatically rolled back. / / default is the timeout value of the underlying transaction system. If the underlying database transaction system does not set the timeout value, then it is none, and there is no timeout limit. Int TIMEOUT_DEFAULT =-1; int getPropagationBehavior (); int getIsolationLevel (); int getTimeout (); boolean isReadOnly (); String getName ();}

3) rollback of transactions in spring:

1) spring recommends rolling back a transaction by throwing an exception. 2) the spring transaction manager catches any unhandled exceptions and then determines whether to roll back the transaction that threw the exception according to the appropriate configuration. 1 > by default, spring rolls back the transaction only if the exception thrown is a runtime unchecked exception, that is, the thrown exception is a subclass of RuntimeException (Errors will also cause transaction rollback), while throwing a checked exception will not cause transaction rollback. 2 > you can configure which exceptions are thrown to roll back transactions, including checked exceptions, or you can specify which exceptions are not rolled back when they are thrown.

4) @ Transactional comment

Attribute type description value String optional qualifying descriptor Specify the transaction manager propagation enum optional transaction propagation behavior settings isolation enum optional transaction isolation level settings readOnly boolean read-write or read-only transactions Default read and write timeout int (in seconds granularity) transaction timeout setting rollbackFor (inheriting Throwable) Class array causing transaction rollback exception class array rollbackForClassName (inheriting Throwable) array of class names causing transaction rollback Exception class name array noRollbackFor (inheriting Throwable) Class array that does not cause transaction rollback noRollbackForClassName (inheriting Throwable) class name array does not cause transaction rollback exception class name array usage: can be written on the class (interface) It can also be done in ways. 1) when acting on a class, all public methods of that class will have transaction properties of that type. 2) you can use this annotation on the method to override the settings at the class level. 3) Spring recommends that you do not use this annotation on interfaces or interface methods, as it takes effect only when using interface-based proxies. 4) if you use this annotation on the methods of private, protected, and default, the annotation will be ignored and no exception will be thrown. 5) by default, only external method calls are captured by the AOP agent, that is, calling other methods within the class does not cause transactional behavior, even if the called method is decorated with the @ Transactional annotation!

5) principle:

1) the transaction management of spring is realized through AOP (dynamic Agent) of spring. A prerequisite for a transaction to take effect in spring: the called method must be intercepted by TransactionInterceptor. Note: only methods that are intercepted by TransactionInterceptor will be added to the transaction management of spring. For example: when calling @ Transactional-modified method B in method A, if method An and method B are in the same class TestClass, the @ Transactional annotation added to method B will not work, because method A's call to method B will not be intercepted by the interceptor! Solution: in method A, use the current proxy object to call method B. Eg: ((TestClass) AopContext.currentProxy ()). B (); 2) for normal transaction management, the autocommit mode of the database must be turned off, and spring sets the autocommit feature of the underlying connection to false. Package org.springframework.jdbc.datasource; public class DataSourceTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, InitializingBean {private DataSource dataSource; / * This implementation sets the isolation level but ignores the timeout. * / [@ Override] (https://my.oschina.net/u/1162528) protected void doBegin (Object transaction, TransactionDefinition definition) {DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; Connection con = null Try {if (txObject.getConnectionHolder () = = null | | txObject.getConnectionHolder () .isSynchronizedWithTransaction ()) {Connection newCon = this.dataSource.getConnection () If (logger.isDebugEnabled ()) {logger.debug ("Acquired Connection [" + newCon + "] for JDBC transaction");} txObject.setConnectionHolder (new ConnectionHolder (newCon), true) } txObject.getConnectionHolder () .setSynchronizedWithTransaction (true); con = txObject.getConnectionHolder () .getConnection (); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction (con, definition); txObject.setPreviousIsolationLevel (previousIsolationLevel) / / 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); / / [spring sets the autocommit of the underlying connection to false]} txObject.getConnectionHolder () .setTransactionActive (true) Int timeout = determineTimeout (definition); if (timeout! = TransactionDefinition.TIMEOUT_DEFAULT) {txObject.getConnectionHolder () .setTimeoutInSeconds (timeout);} / / Bind the session holder to the thread. If (txObject.isNewConnectionHolder ()) {TransactionSynchronizationManager.bindResource (getDataSource (), txObject.getConnectionHolder ());} catch (Throwable ex) {DataSourceUtils.releaseConnection (con, this.dataSource) Throw new CannotCreateTransactionException ("Could not open JDBC Connection for transaction", ex);

6) configuration file:

1) Note form: spring + mybatis: note: mybatis will automatically participate in the management of spring transactions without additional configuration, as long as the data source referenced by org.mybatis.spring.SqlSessionFactoryBean is the same as that referenced by DataSourceTransactionManager, otherwise transaction management will not work. Spring + hibernate: 2) the form of section: To this point I believe you have a deeper understanding of "what is the business in spring", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report