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

SpringBoot (14): using SQL relational databases-transaction processing

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

The four characteristics of transactions (ACID)

Atomicity:

A transaction is an atomic operation consisting of a series of actions. The atomicity of the transaction ensures that the action is either completely complete or completely ineffective.

Consistency (Consistency):

Once the transaction completes (whether successfully or not), the system must ensure that the business it models is in a consistent state and not partially complete and partially fail. Data in reality should not be corrupted.

Isolation:

There may be many transactions processing the same data at the same time, so each transaction should be isolated from the others to prevent data corruption.

Durability:

Once the transaction is complete, no matter what system error occurs, its outcome should not be affected so that it can recover from any system crash. Typically, the result of a transaction is written to persistent storage.

II. Communication behavior

When a transaction method is invoked by another transaction method, you must specify how the transaction should propagate.

For example, a method may continue to run in an existing transaction, or it may start a new transaction and run in its own transaction.

Spring defines seven propagation behaviors.

2.1、PROPAGATION_REQUIRED

Indicates that the current method must run in a transaction. If the current transaction exists, the method will run in that transaction. Otherwise, a new transaction is started, Spring defaults to

2.2、PROPAGATION_SUPPORTS

Indicates that the current method does not require a transaction context, but that the method will run in the current transaction if one exists

2.3、PROPAGATION_MANDATORY

Indicates that the method must be run in a transaction, and throws an exception if the current transaction does not exist

2.4、PROPAGATION_REQUIRED_NEW

Indicates that the current method must run in its own transaction. A new transaction will be started. If there is a current transaction, the current transaction is suspended for the duration of this method. If you are using JTA TransactionManager, you need to access TransactionManager

2.5、PROPAGATION_NOT_SUPPORTED

Indicates that the method should not run in a transaction. If there is a current transaction, the current transaction is suspended while the method is running. If you are using JTA TransactionManager, you need to access TransactionManager

2.6、PROPAGATION_NEVER

Indicates that the current method should not run in a transaction context. An exception is thrown if there is currently a transaction running

2.7、PROPAGATION_NESTED

Indicates that if there is already a transaction, the method will run in nested transactions. Nested transactions can be committed or rolled back independently of the current transaction. If the current transaction does not exist, it behaves like PROPAGATION_REQUIRED. Note that vendor support for this behavior varies. You can consult the documentation of the resource manager to confirm that they support nested transactions

III. Isolation level

Isolation levels define the extent to which a transaction may be affected by other concurrent transactions.

3.1、ISOLATION_DEFAULT

Use the default isolation level of backend database, Spring default, mysql default isolation level: Repeatable Read()

3.2、ISOLATION_READ_UNCOMMITTED

Read Uncommitted, the lowest isolation level that allows reading of uncommitted data changes, which may result in dirty reads, phantom reads, or non-repeatable reads

3.3、ISOLATION_READ_COMMITTED

Read committed, allowing reads of committed data from concurrent transactions, preventing dirty reads, but phantom or non-repeatable reads are still possible

3.4、ISOLATION_REPEATABLE_READ

Repeatable reads, multiple reads of the same field are consistent unless the data is modified by the transaction itself, which prevents dirty reads and non-repeatable reads, but phantom reads can still occur.

3.5、ISOLATION_SERIALIZABLE

Serializable, highest isolation level, fully ACID compliant isolation level, ensures that dirty reads, non-repeatable reads, and phantom reads are prevented, and slowest transaction isolation level, as it is typically achieved by fully locking database tables associated with transactions

Dirty reads:

Dirty reads occur when one transaction reads data that another transaction overwrites but has not yet committed. If the overwrite is later rolled back, the data retrieved by the first transaction is invalid.

Non-repeatable read:

Non-repeatable reads occur when a transaction executes the same query two or more times, but gets different data each time. This is usually because another concurrent transaction updates between queries.

Phantom read:

Fantasy reading is similar to unrepeatable reading. It occurs when a transaction (T1) reads a few rows of data and then another concurrent transaction (T2) inserts some data. In subsequent queries, the first transaction (T1) finds additional records that do not exist.

IV. Operation

Property Description @Transactional

isolation: used to specify the isolation level of the transaction. The default is the isolation level of the underlying transaction.

b. noRollbackFor: Specifies that the transaction is not rolled back when the specified exception is encountered.

c. noRollbackForClassName: Specifies that the transaction will not be rolled back if specified exceptions are encountered. This property can specify multiple exception class names.

d. propagation: Specifies the propagation properties of the transaction.

readOnly: Specifies whether the transaction is read-only. Indicates that the transaction reads data but does not update data, which helps the database engine optimize the transaction. If it is a read-only database, readOnly=true should be set.

f, rollbackFor: Specifies that the transaction is forced to roll back when a specified exception is encountered.

g. rollbackForClassName: Specifies that the transaction is forced to roll back when specified exceptions are encountered. This property can specify multiple exception class names.

h, timeout: Specifies the timeout period of the transaction.

Note:

mysql, for example, storage engine cannot use MyISAM, should use InnoDB

package com.example.demo.service;import com.example.demo.mapper.UserLogMapper;import com.example.demo.mapper.UserMapper;import com.example.demo.pojo.User;import com.example.demo.pojo.UserLog;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Date;/** * Description * * @Author: I Love Big Gold * @Description: Description * @Date: Create in 10:18/6/22/2017 */@Servicepublic class UserService { @Autowired private UserMapper userMapper; @Autowired private UserLogMapper userLogMapper; /** * user registration * * @return */ @Transactional public String register(String name, String ip) { // 1. Add User User user = new User(); user.setName(name); user.setCreateTime(new Date()); userMapper.insert(user); //Test usage boolean flag = true; if (flag) { throw new RuntimeException(); } // 2. Add registration log UserLog userLog = new UserLog(); userLog.setUserName(name); userLog.setUserIp(ip); userLog.setCreateTime(new Date()); userLogMapper.insert(userLog); return "success"; }}

Testing:

package com.example.demo;import com.example.demo.service.UserService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.Date;@RunWith(SpringRunner.class)@SpringBootTestpublic class Springboot3ApplicationTests { @Autowired private UserService userService; @Test public void register() { String result = userService.register("Zhang San", "192.168.1.1"); System.out.println(result); }}

Effect:

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: 271

*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