Springboot (14): Using SQL relational database-transaction processing

Source: Internet
Author: User

I. Four characteristics of a transaction (ACID)

Atomicity (atomicity):

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


Consistency (consistency):

Once a transaction has completed (either successfully or unsuccessfully), the system must ensure that the business it is modeling is in a consistent state, not partially completed partial failure. In reality the data should not be destroyed.


Isolation (Isolation):

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


Persistence (Durability):

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


Ii. dissemination of acts

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

For example: The method might continue to run in an existing transaction, or it might open a new transaction and run in its own transaction.


Spring defines seven propagation behaviors.

2.1, Propagation_required

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

2.2, Propagation_supports

Indicates that the current method does not require a transaction context, but if there is a current transaction, the method runs in this transaction

2.3, Propagation_mandatory

Indicates that the method must 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 be running in its own transaction. A new transaction will be started. If there is a current transaction, the current transaction is suspended during the execution of the method. If you use Jtatransactionmanager, 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 will be suspended while the method is running. If you use Jtatransactionmanager, you need to access TransactionManager

2.6, Propagation_never

Indicates that the current method should not run in the transaction context. If a transaction is currently running, an exception is thrown

2.7, propagation_nested

Indicates that if a transaction already exists, the method will run in a nested transaction. Nested transactions can be individually committed or rolled back independently of the current transaction. If the current transaction does not exist, then its behavior is the same as propagation_required. Note that each vendor's support for this kind of communication behavior is different. You can refer to the Resource Manager's documentation to confirm that they support nested transactions

Third, isolation level

The isolation level defines the degree to which a transaction may be affected by other concurrent transactions.


3.1, Isolation_default

Using the default isolation level of the backend database, spring defaults to the default isolation level of MySQL: Repeatable read (REPEATABLE Read)

3.2, isolation_read_uncommitted

READ UNCOMMITTED, lowest isolation level, allows reading of data changes that have not yet been committed and may result in dirty reads, Phantom reads, or non-repeatable reads

3.3, isolation_read_committed

Read Committed, allowing reading of data that has been committed by concurrent transactions, can prevent dirty reads, but phantom or non-repeatable reads can still occur

3.4, Isolation_repeatable_read

Repeatable reads, which are consistent for multiple reads of the same field, unless the data is modified by its own transaction to prevent dirty reads and non-repeatable reads, but Phantom reads can still occur

3.5, Isolation_serializable

Serializable, the highest isolation level, full compliance with the ACID isolation level, ensures that dirty reads, non-repeatable reads, and Phantom reads are also the slowest transaction isolation levels, because it is typically implemented by fully locking transaction-related database tables


Dirty reads (Dirty reads):

Dirty reads occur when one transaction reads data that has been overwritten by another transaction but has not yet been committed. If the rewrite is later rolled back, the data obtained by the first transaction is invalid.


Non-repeatable read (nonrepeatable Read):

Non-repeatable reads occur when a transaction executes the same query two or more times or more than two times, but each time a different data is obtained. This is usually because another concurrent transaction was updated during two queries.


Phantom Read (Phantom Read):

Phantom reads are similar to non-repeatable reads. It occurs when a transaction (T1) reads a few rows of data, and then another concurrent transaction (T2) inserts some data. In the subsequent query, the first transaction (T1) will find a number of records that do not already exist.


Four, operation

Property Description @Transactional

A, isolation: the isolation level used to specify 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 is not rolled back when a specified number of exceptions are encountered. This property can specify multiple exception class names.

D, Propagation: Specifies the propagation properties of the transaction.

E, ReadOnly: Specifies whether the transaction is read-only. Indicates that the transaction reads only the data but does not update the data, which helps the database engine to optimize the transaction. If it's really a read-only database, you should set Readonly=true

F, Rollbackfor: Specifies that the transaction is forced to roll back when the specified exception is encountered.

G, Rollbackforclassname: Specifies that a transaction is forced to roll back when a specified number of exceptions are encountered. This property can specify multiple exception class names.

H, timeout: Specifies the timeout period for the transaction.


Note

For MySQL, for example, the storage engine cannot use MyISAM and 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 2017/6/22 */@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 Use          boolean flag = true;        if  (flag)  {             throw new runtimeexception ();         }        // 2. Add Registration Log     &nbsP;   userlog userlog = new userlog ();         userlog.setusername (name);         userlog.setuserip (IP);         userlog.setcreatetime (New date ());         userlogmapper.insert (Userlog);         return  "Success";     }}


Test:

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:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/99/AD/wKiom1lLLm3wCCMYAAINEgqiGjg020.png "title=" L ( Lpcv{fg~2p4n7itosy$tn.png "alt=" Wkiom1lllm3wccmyaainegqigjg020.png "/>


650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/99/AD/wKioL1lLLoeBTptfAAAlBngBUJc962.png "title=" Zau9b9iy6d{{~] ' lzds}9et.png "alt=" wkiol1llloebtptfaaalbngbujc962.png "/> 650) this.width=650;" Src= "https:// S2.51cto.com/wyfs02/m00/99/ad/wkiol1lllyoy2wkqaaa2ngggbda740.png "title=" $12{kto$7[) [2L3Q]$] G) $T. png "alt=" Wkiol1lllyoy2wkqaaa2ngggbda740.png "/>



This article is from "I Love Big gold" blog, please be sure to keep this source http://1754966750.blog.51cto.com/7455444/1940824

Springboot (14): Using SQL relational database-transaction processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.