search
HomeJavajavaTutorialSpringBoot transaction management example analysis

1. Definition of transaction

A transaction is a logical execution unit consisting of a sequence of N-step database operations. This series of operations is either all executed or all given up.

2. Characteristics of transactions

Characteristics of transactionsACID:

  • Atomicity: Transactions are indivisible in the application Minimum execution body

  • Consistency: The result of transaction execution must make the data change from one consistency state to another consistency state

  • Isolation Persistence: The execution of each transaction does not interfere with each other, and the internal operations of any transaction are isolated from other transactions

  • Persistence: Once the transaction is submitted, any modifications to the data must Recorded in permanent storage

3. Transaction isolation

Common concurrency exceptions

  • The first type of lost update , The second type of lost update

  • Dirty read, non-repeatable read, phantom read

Common isolation levels

  • Read Uncommitted: Read uncommitted data

  • Read Committed: Read submitted data

  • Repeatable Read: Repeatable read

  • Serializable: Serialization

The first type of update loss: the rollback of a transaction causes another transaction to have Updated data is lost.

The second type of update loss: the submission of a certain transaction causes the data updated by another transaction to be lost.

Dirty read: A certain transaction reads uncommitted data from another transaction.

Non-repeatable reading: The results of a certain transaction reading the same data before and after are inconsistent.

Phantom reading: In a certain transaction, the number of rows queried before and after the same table is inconsistent.

##Read UncommittedYesYesYesYesYes##Read Commited##Repeatable ReadNoNoNoNoYesRepeatable ReadNoNoNoNoNo4. Transaction management
Isolation level First type of lost update Dirty read Second type of lost update Unrepeatable Read Phantom Read
No No Yes Yes Yes
Implementation mechanism

pessimistic Lock (database)

Shared lock (S lock): After transaction A adds a shared lock to certain data, other transactions can only add shared locks to the data, but cannot add exclusive locks.
  • Exclusive lock (X lock): After transaction A adds an exclusive lock to certain data, other transactions can neither add shared locks nor exclusive locks to the data.
  • Optimistic locking (custom)

Version number, timestamp, etc.
  • Updating Before retrieving data, check whether the version number has changed. If a change occurs, cancel this update, otherwise update the data (version number 1)
  • Spring transaction management
Declarative transaction

Declare the transaction characteristics of a method through XML configuration.
  • Declare the transaction characteristics of a method through annotations.
  • Programmatic transactions

Manage transactions through TransactionTemplate and perform database operations through it.
  • 5. Example
  • package com.nowcoder.community.service;
    import com.nowcoder.community.dao.AlphaDao;
    import com.nowcoder.community.dao.DiscussPostMapper;
    import com.nowcoder.community.dao.UserMapper;
    import com.nowcoder.community.entity.DiscussPost;
    import com.nowcoder.community.entity.User;
    import com.nowcoder.community.util.CommunityUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.TransactionDefinition;
    import org.springframework.transaction.TransactionStatus;
    import org.springframework.transaction.annotation.Isolation;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.transaction.support.TransactionCallback;
    import org.springframework.transaction.support.TransactionTemplate;
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    import java.util.Date;
    @Service
    //@Scope("prototype")
    public class AlphaService {
        @Autowired
        private AlphaDao alphaDao;
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private DiscussPostMapper discussPostMapper;
        @Autowired
        private TransactionTemplate transactionTemplate;
        public AlphaService() {
    //        System.out.println("实例化AlphaService");
        }
        @PostConstruct
        public void init() {
    //        System.out.println("初始化AlphaService");
        }
        @PreDestroy
        public void destroy() {
    //        System.out.println("销毁AlphaService");
        }
        public String find() {
            return alphaDao.select();
        }
        // REQUIRED: 支持当前事务(外部事务),如果不存在则创建新事务.
        // REQUIRES_NEW: 创建一个新事务,并且暂停当前事务(外部事务).
        // NESTED: 如果当前存在事务(外部事务),则嵌套在该事务中执行(独立的提交和回滚),否则就会REQUIRED一样.
        @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
        public Object save1() {
            // 新增用户
            User user = new User();
            user.setUsername("alpha");
            user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
            user.setPassword(CommunityUtil.md5("123" + user.getSalt()));
            user.setEmail("alpha@qq.com");
            user.setHeaderUrl("https://cache.yisu.com/upload/information/20220823/112/6198.png");
            user.setCreateTime(new Date());
            userMapper.insertUser(user);
            // 新增帖子
            DiscussPost post = new DiscussPost();
            post.setUserId(user.getId());
            post.setTitle("Hello");
            post.setContent("新人报道!");
            post.setCreateTime(new Date());
            discussPostMapper.insertDiscussPost(post);
            Integer.valueOf("abc");
            return "ok";
        }
        public Object save2() {
            transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
            transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            return transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus status) {
                    // 新增用户
                    User user = new User();
                    user.setUsername("beta");
                    user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
                    user.setPassword(CommunityUtil.md5("123" + user.getSalt()));
                    user.setEmail("beta@qq.com");
                    user.setHeaderUrl("https://cache.yisu.com/upload/information/20220823/112/6199.png");
                    user.setCreateTime(new Date());
                    userMapper.insertUser(user);
                    // 新增帖子
                    DiscussPost post = new DiscussPost();
                    post.setUserId(user.getId());
                    post.setTitle("你好");
                    post.setContent("我是新人!");
                    post.setCreateTime(new Date());
                    discussPostMapper.insertDiscussPost(post);
                    Integer.valueOf("abc");
                    return "ok";
                }
            });
        }
    }

The above is the detailed content of SpringBoot transaction management example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft