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

Spring Learning Notes transaction (1)

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

Lu Chunli's work notes are not as good as bad notes.

A transaction is a unit of work composed of a series of operations, which is inseparable, that is, either all operations are done or none are done. This is a transaction.

Transactions must meet the characteristics of ACID (atomicity, consistency, isolation, and persistence), all of which are indispensable:

Atomicity (Atomicity): that is, a transaction is an indivisible minimum unit of work, with either all or none of the operations within the transaction.

Consistency: the database data is in the correct state before the transaction execution, but the database data is still in the correct state after the transaction execution is completed.

Isolation: there is no impact between concurrent transaction execution, and operations within one transaction have no impact on other transactions

Durability: once a transaction executes successfully, its changes to the data in the database must be permanent.

In actual project development, database operations are generally executed concurrently, that is, multiple transactions are executed concurrently, and concurrent execution may encounter problems. The common problems are as follows:

Update loss: two transactions update a row of data at the same time, and the update of the last transaction overwrites the update of the first transaction, resulting in the data loss of the first transaction update, which is caused by no locking.

Dirty reading: one transaction sees updated data uncommitted by another transaction

Non-repeatable reading: in the same transaction, the same data is read multiple times but different results are returned; that is, other transactions change the data

Illusion: during execution, one transaction reads the inserted data committed by another transaction; that is, a batch of data is read at the beginning of the first transaction, but then another transaction inserts the new data and commits it. At this time, the first transaction reads the data but finds that there is one more item, that is, as if a hallucination had occurred.

In order to solve these concurrency problems, database isolation levels are required, and four isolation levels are defined in the standard SQL specification:

Read uncommitted (Read Uncommitted): at the lowest isolation level, a transaction can read update data uncommitted by other transactions, which is very insecure, and may cause update loss, dirty reading, non-repeatable reading, and phantom reading.

Read committed (Read Committed): a transaction can read the update data submitted by another transaction, cannot see the uncommitted update data, and may not have lost updates or dirty reads, but may have unrepeatable readings and phantom readings.

Repeatable Read: guarantees that multiple queries executed successively in the same transaction will return the same result, unaffected by other transactions, and may cause missing updates, dirty reads, non-repeatable reads, but phantom readings

Serialization (Serializable): the highest isolation level, does not allow transactions to execute concurrently, but must be serialized, the most secure, there can be no updates, dirty reads, non-repeatable reads, phantom reads.

Database transaction types include local transactions and distributed transactions:

Local affairs: general affairs, ACID operated by a single database

Distributed transactions: transactions that span multiple homogeneous or heterogeneous databases.

Java transaction types are JDBC transaction and JTA transaction:

JDBC transactions: manage transactions through the control of Connection objects

JTA transaction: JTA refers to Java transaction API (Java Transaction API), which is the Java EE database transaction specification. JTA only provides transaction management interface and is implemented by application server vendors (such as WebSphere Application Server). JTA transaction is more powerful than JDBC and supports distributed transactions.

In JDBC mode, programmers obtain database connections, perform data operations, and control transactions, such as:

Package com.invicme.apps.tx.jdbc;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;/** @ author lucl * * tools for JDBC database connections * * / public class DbHelper {/ * / private static String driver = null; private static String url = null; private static String username = null Private static String password = null; static {/ / the properties configuration file is located in the same directory as the utility class: InputStream in = DbHelper.class.getResourceAsStream ("jdbc.properties"); Properties props = new Properties (); try {props.load (in);} catch (IOException e) {e.printStackTrace () } driver = props.getProperty ("jdbc.driver"); url = props.getProperty ("jdbc.url"); username = props.getProperty ("jdbc.username"); password = props.getProperty ("jdbc.password");} / * * obtain database connection * * @ return * / public Connection getCon () {Connection con = null Try {Class.forName (driver). NewInstance (); / MYSQL driver con = DriverManager.getConnection (url, username, password); / / Link local MYSQL} catch (Exception e) {con = null; e.printStackTrace ();} return con } / * * close database connection * * @ param con * @ throws SQLException * / public void closeCon (Connection con) throws SQLException {if (null! = con) {con.close ();}

Unit test class

Package com.test.apps.spring.tx;import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.SQLException;import java.sql.Statement;import org.apache.log4j.Logger;import org.junit.Test;import com.invicme.apps.tx.jdbc.DbHelper;/** @ author lucl * * / public class TestJdbcTransaction {/ / private static final Logger logger = Logger.getLogger (TestJdbcTransaction.class) @ Test public void testJdbcTransaction () {DbHelper dbHelper = new DbHelper (); Connection con = dbHelper.getCon (); try {DatabaseMetaData metaData = con.getMetaData (); / * * basic database information * / MySQL String databaseProductName = metaData.getDatabaseProductName () / / 5.6.17-log String databaseProductVersion = metaData.getDatabaseProductVersion (); / / 5 int databaseMajorVersion = metaData.getDatabaseMajorVersion (); / / 6 int databaseMinorVersion = metaData.getDatabaseMinorVersion (); / / MySQL 5.6.17-log logger.info (databaseProductName + "" + databaseProductVersion) / / 5.6 logger.info (databaseMajorVersion + "." + databaseMinorVersion); int defaultTransactionIsolation = metaData.getDefaultTransactionIsolation (); / / transaction isolation level: 2 logger.info (defaultTransactionIsolation); boolean supportsTransactions = metaData.supportsTransactions (); / / whether transactions are supported: true logger.info (supportsTransactions) String driverName = metaData.getDriverName (); String driverVersion = metaData.getDriverVersion (); int driverMajorVersion = metaData.getDriverMajorVersion (); int driverMinorVersion = metaData.getDriverMinorVersion (); / / MySQL Connector Java logger.info (driverName); / / mysql-connector-java-5.1.38 (Revision: fe541c166cec739c74cc727c5da96c1028b4834a) logger.info (driverVersion) / / 5.1 logger.info (driverMajorVersion + "." + driverMinorVersion);} catch (SQLException e) {e.printStackTrace ();} try {/ / turn off autocommit con.setAutoCommit (false); Statement statement = con.createStatement () Statement.executeUpdate ("update user set name='zhangsan' where name='lisi'"); / / transaction commit con.commit ();} catch (SQLException e) {e.printStackTrace (); / / transaction rollback try {con.rollback () } catch (SQLException E1) {e1.printStackTrace ();}} finally {try {dbHelper.closeCon (con);} catch (SQLException e) {e.printStackTrace ();}

Description:

In JDBC2.0, transactions can only be commit or rollback;, while JDBC3.0 introduces the SavePoint feature, which allows transactions to be divided into multiple phases.

Savepoint savepoint = con.setSavepoint ("svpt"); / / .con.rollback (savepoint)

Spring simplifies this process by providing two transaction control modes: declarative transactions (annotated and XML configuration) and programmatic transactions.

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

Database

Wechat

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

12
Report