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 transaction Control in the introduction to spring Framework

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what is transaction control in the introduction of spring framework". 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 transaction control in the introduction to the spring framework"?

1. About transaction control

A transaction is a series of actions that together make a complete unit of work, which must be completed, and if one fails, the transaction rolls back to its original state as if nothing had happened.

1.1 transaction Control API in spring

The PlatformTransactionManager interface provides methods for transaction operations, including three specific operations

Public interface PlatformTransactionManager extends TransactionManager {/ / get transaction status information TransactionStatus getTransaction (@ Nullable TransactionDefinition var1) throws TransactionException; / / commit transaction void commit (TransactionStatus var1) throws TransactionException; / / rollback transaction void rollback (TransactionStatus var1) throws TransactionException;}

Implementation classes commonly used in development:

Org.springframework.jdbc.datasource.DataSourceTransactionManager: used when persisting data using Spring JDBC or iBatis

The structure of transaction Control Interface in spring

1.1.2 TransactionDefinition

The definition information object of the transaction, which includes the following methods:

Get the transaction object name: String getName ()

Get transaction isolation level: int getIsolationLevel ()

Get transaction propagation behavior: int getPropagationBehavior ()

Get transaction timeout: int getTimeout ()

Get whether the transaction is read-only: boolean isReadOnly ()

1.1.3 TransactionStatus

Describes the state information of the transaction object at a certain point in time, including six specific operations:

Refresh transaction: void flush ()

Get whether there is a storage point: boolean hasSavepoint ()

Get whether the transaction is completed: boolean isCompleted ()

Get whether the transaction is new: boolean isNewTransaction ()

Get whether the transaction is rolled back: boolean isRollbackOnly ()

Set transaction rollback: void set RollbackOnly ()

1.2 isolation level of the transaction

The isolation sector of the transaction reflects the attitude towards concurrent access when the transaction is committed.

1.2.1 level of transaction isolation

The default level of ① ISOLATION_DEFAULT, which is determined by the default setting of DBA, belongs to one of the following

A ② ISOLATION_READ_UNCOMMITTED is a transaction that can read data from another uncommitted transaction. There will be dirty reading, unrepeatable reading, and phantom reading (lowest isolation level, but high concurrency)

③ ISOLATION_READ_COMMITTED means that a transaction can not read data until another transaction is committed, thus solving the problem of dirty reading. There will be non-repeatable reading, phantom reading problems (locking rows being read, for most systems, Oracle default level)

④ ISOLATION_REPEATABLE_READ is when you start to read data (transaction starts), you are no longer allowed to modify the operation, solving the problem of non-repeatable reading. Phantom reading problems occur (lock all rows read, MYSQL default level)

⑤ ISOLATION_SERALZABLE is the highest transaction isolation level, at which transactions are serialized and executed sequentially, avoiding dirty, unrepeatable, and phantom reads. However, this transaction isolation level is inefficient, consumes database performance, and is generally not used. (lock the table)

The transaction isolation level increases from top to bottom, and the higher the isolation level, the more you can ensure the integrity and consistency of the data. However, the consumption of database performance increases in turn, and the concurrent execution efficiency decreases in turn.

Most databases default to Read Commited isolation level, such as SqlServer, Oracle

The default isolation level for a few databases is: Repeatable Read, for example: MySQL InnoDB

1.2.2 three problems that will occur when reading a database

① Dirty reads: read dirty data.

In other words, if the uncommitted (and still cached) data of transaction An is read by transaction B, if transaction A fails to roll back, it will cause the data read by transaction B to be wrong.

② non-repeatable reads: data cannot be read repeatedly.

For example, the value of reading data price at two places in transaction A. On the first reading, price is 100, and then transaction B changes the value of price to 200; transaction A reads it again, and it turns out that price becomes 200, resulting in transaction A data confusion.

③ phantom reads: Phantom reads data.

Similar to non-repeatable reads, this is also a problem of multiple read inconsistencies in the same transaction. But the inconsistency of non-repeatable reads is because the data value he wants to fetch has been changed (such as price), while the inconsistency of the data that phantom reads wants to read is that his conditional data set has changed.

For example, when executing Select account.id where account.name= "Bruce*" and reading six eligible id; for the first time, transaction B changes the name of an account from "dd" to "Bruce1". As a result, seven data are fetched.

The key point of unrepeatable reading is modification: under the same condition, two readings find that the values are not the same.

The focus of phantom reading is to add or delete: under the same condition, the number of records found by the two reads is not the same.

1.2.3 Association between data isolation levels and problems that arise

Propagation behavior of Dirty readsnon-repeatable readsphantom readsREAD_UNCOMMITTEDYYYREAD_COMMITTEDNYYREPEATABLE_READNNYSERALZABLENNN1.3 transactions

REQUIRED: if there is no current transaction, create a new transaction, and if one already exists, join it. General selection (default)

SUPPORTS: supports the current transaction and executes in a non-transactional manner if there is no transaction (no transaction)

MANDATORY: uses the current transaction and throws an exception if there is no current transaction.

REQUERS_NEW: create a new transaction and suspend the current transaction if it is currently in the transaction.

NOT_SUPPORTED: performs the operation in a non-transactional manner, suspending the current transaction if there is a current transaction.

NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.

NESTED: if a transaction currently exists, it is executed within a nested transaction. If there is no transaction currently, perform a similar operation to REQUIRED.

1.4 timeout

Refers to the maximum amount of time a transaction can wait after it is committed, which will fail automatically. The default value is-1 and there is no time limit. If so, it is set in seconds.

1.5 is a read-only transaction

Read-write transaction: start a transaction when adding, deleting, or modifying

Read-only transaction: when a query is executed, the transaction is also opened

two。 Configuration steps of transaction Control configuration 2.1 based on xml

Configure the transaction manager

Configure notification of transactions

At this point, we need to import transaction constraints tx namespaces and constraints, as well as aop's use of tags to configure transaction notifications.

Id: gives a unique identity to the transaction notification

Transaction-manager: provide a transaction manager reference for transaction notification

Configure a generic pointcut expression in AOP

Establish the correspondence between transaction notification and pointcut expression

The properties of the configured transaction are inside the notification label of the transaction

2.2 configure the properties of the transaction

Isolation: used to specify the isolation level of the transaction. The default value is DEFAULT, which means that the default isolation level of the database is used.

Propagation: used to specify the propagation behavior of the transaction. The default value is REQUIRED, which means that there must be transactions. Add, delete and modify options. The query method can be selected as SUPPORTS.

Read-only: used to specify whether the transaction is read-only. Only the query method can be set to true. The default value is false, which means read and write.

Timeout: used to specify the timeout of the transaction. The default value is-1, which means that it never times out. If a numeric value is specified, in seconds.

Rollback-for: used to specify an exception, when the exception is generated, the transaction rolls back, and when other exceptions occur, the transaction does not roll back. There is no default value. Indicates that any exception is rolled back.

No-rollback-for: used to specify an exception, when the exception is generated, the transaction does not roll back, and when other exceptions occur, the transaction rolls back. There is no default value. Indicates that any exception is rolled back.

Code example:

3. Annotation-based transaction control configuration 3.1 configuration steps

① Writing configuration Class

② injects objects into the IoC container for management

③ adds transaction comments to the business and indicates the transaction attributes

Code example:

① configuration spring

@ Configuration// declares @ ComponentScan ("cn.bruce") / / declares packages to be scanned @ Import ({JdbcConfig.class, TransactionConfig.class}) / / imports other configuration classes @ PropertySource ("jdbcConfig.properties") / / imports configuration file @ EnableAspectJAutoProxy (proxyTargetClass = true) / / enables annotation support @ EnableTransactionManagement// to enable transaction control public class SpringConfiguration {}

② configuration jdbc

Public class JdbcConfig {@ Value ("${jdbc.driver}") private String driver; @ Value ("${jdbc.url}") private String url; @ Value ("${jdbc.username}") private String username; @ Value ("${jdbc.password}") private String password / * create a data source object * @ return * / @ Bean ("dataSource") public DataSource creatDataSource () {DriverManagerDataSource dataSource = new DriverManagerDataSource (); dataSource.setDriverClassName (driver); dataSource.setUrl (url); dataSource.setUsername (username); dataSource.setPassword (password); return dataSource } / * * create JdbcTemplate * @ param dataSource * @ return * / @ Bean (name = "jdbcTemplate") public JdbcTemplate creatJdbcTemplate (DataSource dataSource) {return new JdbcTemplate (dataSource);}}

③ configure transaction controller

Public class TransactionConfig {/ * is used to create transaction manager objects * @ param dataSource * @ return * / @ Bean (name = "transactionManager") public PlatformTransactionManager creatTransactionManager (DataSource dataSource) {return new DataSourceTransactionManager (dataSource);}}

④ injects Dao and Service layer objects into the IoC container through [@ Repository] (https://my.oschina.net/u/3055569) and [@ service] (https://my.oschina.net/service) annotations)

⑤ uses [@ Transactional] (https://my.oschina.net/u/3770144) annotations for transaction configuration at the business layer

/ / configure @ Transactional (propagation = Propagation.REQUIRED, readOnly = false) @ Overridepublic void transfer (String sourceName, String targetName, Float money) {System.out.println ("start the transfer operation.") ; Account source = accountDao.getAccountByName (sourceName); Account target = accountDao.getAccountByName (targetName); source.setMoney (source.getMoney ()-money); target.setMoney (target.getMoney () + money); accountDao.updateAccount (source); int I = 1gam0; accountDao.updateAccount (target); System.out.println ("transfer completed.") ;}

⑥ writing test class for testing

3.2 Notes involved

[@ Transactional] (https://my.oschina.net/u/3770144) this annotation is equivalent to * in xml configuration for transaction configuration, and its attribute meaning is the same as that in xml.

This annotation can be used on interfaces, classes, and methods:

Appears on an interface, indicating that all implementation classes of this interface have transaction support

Appears on the class, indicating that all methods of the class have transaction support

Appears on the method, indicating that the method has transaction support

Priority of the above three locations: method > class > interface

At this point, I believe you have a deeper understanding of "what is transaction control in the introduction to the spring framework". 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

Development

Wechat

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

12
Report