Spring--事务管理

主要内容:

Spring--事务管理_第1张图片

 

Spring--事务管理_第2张图片


数据库表结构:

Spring--事务管理_第3张图片

建表语句: 

drop database if exists os;
create database os;
use os;
drop table if exists orders;

drop table if exists products;

/*==============================================================*/
/* Table: orders                                                */
/*==============================================================*/
create table orders
(
   id                   char(6) not null,
   products_id          char(6) not null,
   number               int,
   price                double,
   create_time          datetime,
   send_time            datetime,
   confirm_time         datetime,
   consignee            varchar(20),
   consignee_phone      char(11),
   consignee_address    varchar(100),
   status               varchar(10),
   primary key (id)
);

/*==============================================================*/
/* Table: products                                              */
/*==============================================================*/
create table products
(
   id                   char(6) not null,
   title                varchar(20),
   price                double,
   stock                int,
   status               varchar(10),
   primary key (id)
);

alter table orders add constraint FK_Reference_1 foreign key (products_id)
      references products (id) on delete restrict on update restrict;

insert into products values('100001','小米8',2699,100,'正常');
insert into products values('100002','小米8SE',1799,100,'正常');
insert into products values('100003','小米MIX2S',3299,100,'正常');
insert into products values('100004','小米手环3',199,100,'正常');

事务概念:

事务的特性:

Spring--事务管理_第4张图片


MySQL数据处理:

Spring--事务管理_第5张图片

测试:rollback

Spring--事务管理_第6张图片

测试:commit

Spring--事务管理_第7张图片


MySQL事务管理--事务并发问题:脏读、不可重复读、幻读
 

 脏读解决方法:使得事务只能访问永久性的数据

Spring--事务管理_第8张图片

不可重复读解决方法:在事务A操作某个记录的时候,不允许别的事务操作该记录 

 

Spring--事务管理_第9张图片

 幻读解决方法:在事务A操作表的时候,进行锁表操作。不允许别的事务对该表进行操作

Spring--事务管理_第10张图片


事务隔离级别:

Spring--事务管理_第11张图片


JDBC事务处理:

Spring--事务管理_第12张图片

测试代码:

package com.imooc.os.dao;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class OrderTest {
    private String driver = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/os?useUnicode=true&characterEncoding=utf8";
    private String userName = "root";
    private String password = "密码";

    @Test
    public void addOrder(){
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,userName,password);
            //首先禁止自动封装提交
            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();
            statement.execute("insert into orders values('100001','100001',2,2499,now(),null,null,'刘备','1330000000','成都','待发货')");
            statement.execute("update products set stock=stock-2 where id='100001'");
            statement.close();
            //手动提交
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //有异常则进行回滚
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

JDBC事务处理--事务隔离级别:

Spring--事务管理_第13张图片


Spring事务管理:

Spring--事务管理_第14张图片


TransationDefinition接口: 

Spring--事务管理_第15张图片


Spring事务传播行为: 

Spring--事务管理_第16张图片


准备工作:引入依赖包、实现持久层、业务层接口的声明

引入依赖包:

        
        
            org.springframework
            spring-core
            5.1.5.RELEASE
        

        
            org.springframework
            spring-beans
            5.1.5.RELEASE
        

        
            org.springframework
            spring-context
            5.1.5.RELEASE
        

        
            org.springframework
            spring-aop
            5.1.5.RELEASE
        

        
            org.springframework
            spring-jdbc
            5.1.5.RELEASE
        

        
            org.springframework
            spring-tx
            5.1.5.RELEASE
        

        
            org.springframework
            spring-test
            5.1.5.RELEASE
        

        
            org.aspectj
            aspectjweaver
            1.8.9
        

实现持久层并配置文件:

Spring--事务管理_第17张图片




    
        
        
        
        
    
    
        
    
    

业务层接口的声明:


Spring事务处理--基于底层API:

OrderServiceImpl:
package com.imooc.os.service.impl1;

import com.imooc.os.dao.OrderDao;
import com.imooc.os.dao.ProductDao;
import com.imooc.os.entity.Order;
import com.imooc.os.entity.Product;
import com.imooc.os.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    public void addOrder(Order order) {
        order.setCreateTime(new Date());
        order.setStatus("待付款");
        TransactionProxyFactoryBean transactionProxyFactoryBean;
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        try {
            orderDao.insert(order);
            Product product = productDao.select(order.getProductsId());
            product.setStock(product.getStock() - order.getNumber());
            productDao.update(product);
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            e.printStackTrace();
            transactionManager.rollback(transactionStatus);
        }
    }
}

spring-service1.xml:



    
    
    
        
    
    
        
    

测试代码:

package com.imooc.os.service;

import com.imooc.os.entity.Order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-service1.xml")
public class OrderTest {

    @Autowired
    private OrderService orderService;
    @Test
    public void testAddOrder(){
        Order order = new Order("100006","100002",2,1799,"","","");
        orderService.addOrder(order);
    }

}

输出结果:

Spring--事务管理_第18张图片


Spring事务管理--基于TransactionTemplte:

package com.imooc.os.service.impl2;

import com.imooc.os.dao.OrderDao;
import com.imooc.os.dao.ProductDao;
import com.imooc.os.entity.Order;
import com.imooc.os.entity.Product;
import com.imooc.os.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private TransactionTemplate transactionTemplate;

    public void addOrder(final Order order) {
        order.setCreateTime(new Date());
        order.setStatus("待付款");

        transactionTemplate.execute(new TransactionCallback() {
            public Object doInTransaction(TransactionStatus transactionStatus) {
                try {
                    orderDao.insert(order);
                    Product product = productDao.select(order.getProductsId());
                    product.setStock(product.getStock() - order.getNumber());
                    productDao.update(product);
                }catch (Exception e){
                    e.printStackTrace();
                    transactionStatus.setRollbackOnly();
                }
                return null;
            }
        });

    }
}

spring-service2.xml:



    
    
    
        
    
    
        
    

测试结果:

package com.imooc.os.service;

import com.imooc.os.entity.Order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-service2.xml")
public class OrderTest {

    @Autowired
    private OrderService orderService;
    @Test
    public void testAddOrder(){
        Order order = new Order("100007","100002",2,1799,"","","");
        orderService.addOrder(order);
    }

}

输出结果:

Spring--事务管理_第19张图片


Spring事务管理--基于拦截器:

Spring--事务管理_第20张图片

Spring--事务管理_第21张图片

实现类:

package com.imooc.os.service.impl;

import com.imooc.os.dao.OrderDao;
import com.imooc.os.dao.ProductDao;
import com.imooc.os.entity.Order;
import com.imooc.os.entity.Product;
import com.imooc.os.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;

    public void addOrder(Order order) {
        order.setCreateTime(new Date());
        order.setStatus("待付款");

        orderDao.insert(order);
        Product product = productDao.select(order.getProductsId());
        product.setStock(product.getStock() - order.getNumber());
        productDao.update(product);

    }
}

配置代码:



    
    
        
    

    

    
        
        
            
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED
            
        
    
    
        
        
            
                
            
        
    

简化拦截器配置:



    
    
        
    
    
    
        
        
            
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED,readOnly
                PROPAGATION_REQUIRED
            
        
        
    

Spring事务处理--基于tx命名空间:

配置文件:



    
    
    
        
    
    
        
            
            
            
            
        
    
    
        
        
    

Spring事务处理--基于注解:

实现类:

package com.imooc.os.service.impl6;

import com.imooc.os.dao.OrderDao;
import com.imooc.os.dao.ProductDao;
import com.imooc.os.entity.Order;
import com.imooc.os.entity.Product;
import com.imooc.os.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductDao productDao;

    @Transactional(propagation = Propagation.REQUIRED)
    public void addOrder(Order order) {
        order.setCreateTime(new Date());
        order.setStatus("待付款");

        orderDao.insert(order);
        Product product = productDao.select(order.getProductsId());
        product.setStock(product.getStock() - order.getNumber());
        productDao.update(product);

    }
}

配置文件:



    
    
    
        
    
    

总结:

Spring--事务管理_第22张图片

 

你可能感兴趣的:(Spring--事务管理)