In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Chapter One. Spring transaction configuration
1. A Transaction is a concurrency control unit and a user-defined sequence of operations.
These operations are either done or not done, which is an indivisible unit of work. Through transactions, SQL Server can bind a set of logically related operations together so that the server can maintain the integrity of the data.
Transactions usually start with Begin,Transaction and end with Commit or Rollback.
Commit: indicates commit, that is, all operations of the commit transaction. Specifically, all the updates to the database in the transaction are written back to the physical database on disk, and the transaction ends normally.
Rollback: indicates rollback, that is, some failure occurs while the transaction is running, and the transaction cannot continue. The system undoes all completed operations on the database in the transaction and rolls back to the state where the transaction started.
two。 Nature of the transaction (ACID feature)
A: an Atomicity transaction is the logical working unit of a database, and all operations included in the transaction are either done or not done.
C: the result of Consistency transaction execution must be to change the database from one consistency state to another. Consistency is closely related to atomicity.
I: Isolation) the execution of one transaction cannot be interfered with by other transactions.
D: persistence / Durability) once a transaction is committed, its changes to the data in the database should be permanent.
3. It is divided into two ways: programmatic transaction management and declarative transaction management.
Programmatic transaction management uses TransactionTemplate or directly uses the underlying PlatformTransactionManager. For programmatic transaction management, spring recommends using TransactionTemplate.
Declarative transaction management is based on AOP. Its essence is to intercept before and after the method, then create or join a transaction before the target method starts, and commit or roll back the transaction according to execution after the target method is executed. The biggest advantage of declarative transactions is that there is no need to manage transactions programmatically, so there is no need to mix transaction management code with business logic code, and transaction rules can be applied to business logic by making relevant transaction rule declarations in the configuration file (or through @ Transactional annotations).
Declarative transaction management is obviously superior to programmatic transaction management, which is the non-intrusive development approach advocated by spring. Declarative transaction management makes the business code uncontaminated, and an ordinary POJO object can be fully supported by annotations. Compared with programmatic transactions, the only drawback of declarative transactions is that the finest granularity of the latter can only work at the method level, not at the code block level as programmatic transactions do. But even if there are such requirements, there are many workarounds, for example, the code blocks that need to be managed by transactions can be separated into methods, and so on.
There are also two common ways of declarative transaction management, one is xml configuration files based on tx and aop namespaces, and the other is based on @ Transactional annotations. Obviously, the annotation-based approach is easier to use and more refreshing.
Spring transaction characteristics
All spring transaction management policy classes inherit from the org.springframework.transaction.PlatformTransactionManager interface
The TransactionDefinition interface defines the following features:
Transaction isolation level
The isolation level refers to the degree of isolation between several concurrent transactions.
Five constants representing the isolation level are defined in the TransactionDefinition interface:
TransactionDefinition.ISOLATION_DEFAULT: this is the default value, which means that the default isolation level of the underlying database is used. For most databases, this value is usually TransactionDefinition.ISOLATION_READ_COMMITTED.
TransactionDefinition.ISOLATION_READ_UNCOMMITTED: this isolation level means that one transaction can read data modified by another transaction that has not yet been committed. This level does not prevent dirty, non-repeatable and phantom reads, so the isolation level is rarely used. For example, PostgreSQL does not actually have this level.
TransactionDefinition.ISOLATION_READ_COMMITTED: this isolation level means that one transaction can only read data that another transaction has committed. This level prevents dirty reading, which is the recommended value in most cases.
TransactionDefinition.ISOLATION_REPEATABLE_READ: this isolation level means that a transaction can execute a query repeatedly throughout the process, and the records returned each time are the same. This level prevents dirty reading and non-repeatable reading.
TransactionDefinition.ISOLATION_SERIALIZABLE: all transactions are executed one by one, so that interference between transactions is completely impossible, that is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this will seriously affect the performance of the program. This level is not usually used.
Transaction propagation behavior
The so-called transaction propagation behavior means that if a transaction context already exists before the start of the current transaction, there are several options to specify the execution behavior of a transactional method. The following constants that represent propagation behavior are included in the TransactionDefinition definition:
TransactionDefinition.PROPAGATION_REQUIRED: if there is a transaction, join it; if there is no transaction, create a new transaction. This is the default value.
TransactionDefinition.PROPAGATION_REQUIRES_NEW: creates a new transaction and suspends the current transaction if it exists.
TransactionDefinition.PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.
TransactionDefinition.PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.
TransactionDefinition.PROPAGATION_NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.
TransactionDefinition.PROPAGATION_MANDATORY: if there is a transaction, join it; if there is no transaction, throw an exception.
TransactionDefinition.PROPAGATION_NESTED: if there is a transaction, a transaction is created to run as a nested transaction of the current transaction; if there is no transaction, this value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.
Transaction timeout: the so-called transaction timeout refers to 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. In TransactionDefinition, the timeout is represented by the value of int, in seconds.
The default setting 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.
Transaction read-only attributes: read-only transactions are used in situations where client code is read-only but do not modify data, and read-only transactions are used for optimization in specific situations, such as when using Hibernate.
The default is a read-write transaction.
"read-only transaction" is not a mandatory option, it is just a "hint" to prompt the database driver and database system that the transaction does not include the operation of changing data, then the JDBC driver and database may make some specific optimizations to the transaction according to this situation, such as not arranging the corresponding database lock, in order to reduce the pressure of the transaction on the database. After all, transactions also consume the resources of the database.
But it's not impossible for you to modify data in a "read-only transaction". It's just that the protection of data consistency is not as safe as a "read-write transaction".
Therefore, "read-only transaction" is only a recommended configuration for performance optimization, and it is not mandatory for you to do so.
Spring transaction rollback rules
The recommended way to instruct the spring transaction manager to roll back a transaction is to throw an exception within the context of the current transaction. The spring transaction manager catches any unhandled exceptions and then decides whether to roll back the transaction that threw the exception based on the rule.
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 the transaction to be rolled back), while throwing a checked exception will not cause the transaction to be rolled back. You can explicitly configure to roll back transactions, including checked exceptions, when those exceptions are thrown. You can also clearly define which exceptions are thrown without rolling back the transaction. You can also programmatically indicate that a transaction must be rolled back through the setRollbackOnly () method, and the only thing you can do after calling setRollbackOnly () is to roll back.
MyBatis as an example Annotation-based declarative transaction Management configuration @ Transactional
Spring.xml
Classpath:mybatis-config.xml com.baobao.persistence.test
Add tx namespace
Xmlns:aop= "http://www.springframework.org/schema/aop" xmlns:tx=" http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-3.0.xsd "
MyBatis automatically participates in spring transaction management without additional configuration, as long as the data source referenced by org.mybatis.spring.SqlSessionFactoryBean is consistent with the data source referenced by DataSourceTransactionManager, otherwise transaction management will not work.
@ Transactional comment
@ Transactionalattribute
Attribute type describes the valueString optional qualifying descriptor, specifies the transaction manager propagationenum: Propagation optional transaction propagation behavior settings isolationenum: Isolation optional transaction isolation level settings readOnlyboolean read-write or read-only transactions, default read-write timeoutint (in seconds granularity) transaction timeout sets the rollbackForClass object array, must inherit from the Throwable-induced transaction rollback exception class array rollbackForClassName class name array Must inherit from Throwable exception class name array that causes transaction rollback, noRollbackForClass object array, must inherit from Throwable exception class array that does not cause transaction rollback, noRollbackForClassName class name array, must inherit from Throwable exception class name array that does not cause transaction rollback
Usage
@ Transactional can act on interfaces, interface methods, classes, and class methods. When acting on a class, all public methods of that class will have transactional properties of that type, and we can also use this annotation at the method level to override the class-level definition.
Although the @ Transactional annotation can be applied to interfaces, interface methods, classes, and class methods, Spring recommends that it not be used on interfaces or interface methods, as it only takes effect when using interface-based proxies. In addition, the @ Transactional annotation should only be applied to public methods, which is determined by the nature of Spring AOP. If you use the @ Transactional annotation on protected, private, or default visibility methods, this will be ignored and no exception will be thrown.
By default, only method calls from outside 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.
@ Autowired private MyBatisDao dao; @ Transactional @ Override public void insert (Test test) {dao.insert (test); throw new RuntimeException ("test"); / / throw unchecked exception, trigger thing, roll back}
NoRollbackFor class, when acting on a class, all public methods of that class will have transaction properties of that type
@ Transactional (noRollbackFor=RuntimeException.class) @ Override public void insert (Test test) {dao.insert (test); / / throws a unchecked exception, triggers a transaction, noRollbackFor=RuntimeException.class, and does not roll back throw new RuntimeException ("test");} @ Transactional public class MyBatisServiceImpl implements MyBatisService {@ Autowired private MyBatisDao dao @ Override public void insert (Test test) {dao.insert (test); / / throws a unchecked exception, triggers a transaction, and rolls back throw new RuntimeException ("test");}
Propagation=Propagation.NOT_SUPPORTED
@ Transactional (propagation=Propagation.NOT_SUPPORTED) @ Override public void insert (Test test) {/ / the propagation behavior of things is PROPAGATION_NOT_SUPPORTED, which runs in a non-transactional manner and is not stored in the database dao.insert (test);}
MyBatis as an example annotation-based declarative transaction management configuration, xml configuration
Mainly for aop section configuration, just look at xml.
How Chapter Two Spring transactions are configured
According to the difference of proxy mechanism, five configuration modes of Spring transaction are summarized. The configuration file is as follows:
The first way: each Bean has an agent
PROPAGATION_REQUIRED
The second way: all Bean share a proxy base class
PROPAGATION_REQUIRED
The third way: use interceptor
PROPAGATION_REQUIRED * Dao transactionInterceptor
The fourth way: use the interceptor configured with the tx tag
Fifth way: full annotations need to add @ Transactional annotations to DAO at this time, as follows: package com.bluesky.spring.dao;import java.util.List;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import org.springframework.stereotype.Component;import com.bluesky.spring.domain.User @ Transactional@Component ("userDao") public class UserDaoImpl extends HibernateDaoSupport implements UserDao {public List listUsers () {return this.getSession () .createQuery ("from User") .list ();}}
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
R download https://cran.r-project.org/Rstudio download https://www.rstudio.com/
© 2024 shulou.com SLNews company. All rights reserved.