美文网首页
spring boot 学习(事务处理)

spring boot 学习(事务处理)

作者: 程序里一块砖 | 来源:发表于2018-01-10 16:23 被阅读0次

此文做记录交流,如有不当,还望指正。

事务(Transaction),一般是指要做的或所做的事情。在计算机中是指访问并可能更新数据库中各种数据项
的一个程序执行单元(unit)。事务(Transaction)是访问并可能更新数据库中各种数据项
的一个程序执行单元(unit)。事务通常由高级数据库操纵语言或编程语言(如SQL,C++或Java)书写的用户程序的执行所引起,并用形如begin transactionend transaction语句(或函数调用)来界定。事务由事务开始(begin transaction)和事务结束(end transaction)之间执行的全体操作组成。

事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。
原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
持久性(durability)。持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。

本节我们测试spring boot 简单配置事务及读写分离的处理
首先按照上节我们创建一个spring boot 项目,mybaties做持久层的处理!
项目创建完成后结构如下:


image.png

spring boot 添加事务处理

我们在我们的service中新增一个insert方法

package com.demo.springboot_mybatis.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.springboot_mybatis.mapper.OrganizationNameMapper;
import com.demo.springboot_mybatis.model.OrganizationName;

@Service
public class OrganizationNameService 
extends AbstractBaseService<OrganizationNameMapper, OrganizationName> {

     public int insertOrganizationName(){
         OrganizationName org1 = new OrganizationName();
         OrganizationName org2 = new OrganizationName();
         OrganizationName org3 = new OrganizationName();
         OrganizationName org4 = new OrganizationName();
         org1.setId(101l);
         org1.setOrganizationName("101");
         org2.setId(102l);
         org2.setOrganizationName("102");
         org3.setId(103l);
         org3.setOrganizationName("103");
         org4.setId(104l);
         org4.setOrganizationName("104");
         this.mapper.insert(org1);
         this.mapper.insert(org2);
         this.mapper.insert(org3);
         this.mapper.insert(org4);
         throw new RuntimeException();
     }
}


controller中调用

package com.demo.springboot_mybatis.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.springboot_mybatis.service.OrganizationNameService;



@RestController
public class RestHelloController {
    
    @Autowired
    OrganizationNameService organizationNameService;
    
    @RequestMapping("/insert")
    public String insert(HttpServletRequest request) throws Exception{
        organizationNameService.insertOrganizationName();
        return "";
    } 
}

启动项目访问http://localhost:8080/insert

image.png
我们发现项目访问出错了,但是依然数据进库了!这是因为我们没有添加事务处理的结果!我们在我们的service中的insert方法上面加上@Transactional后,并更改我们插入的数据
 @Transactional
     public int insertOrganizationName(){
         OrganizationName org1 = new OrganizationName();
         OrganizationName org2 = new OrganizationName();
         OrganizationName org3 = new OrganizationName();
         OrganizationName org4 = new OrganizationName();
         org1.setId(105l);
         org1.setOrganizationName("105");
         org2.setId(106l);
         org2.setOrganizationName("106");
         org3.setId(107l);
         org3.setOrganizationName("107");
         org4.setId(108l);
         org4.setOrganizationName("108");
         this.mapper.insert(org1);
         this.mapper.insert(org2);
         this.mapper.insert(org3);
         this.mapper.insert(org4);
         throw new RuntimeException();
     }

重新启动我们的项目访问http://localhost:8080/insert

image.png
我们发现访问依然报错,但是数据是没有入库的
image.png
我们取消我们方法中的throw后
 @Transactional
     public int insertOrganizationName(){
         OrganizationName org1 = new OrganizationName();
         OrganizationName org2 = new OrganizationName();
         OrganizationName org3 = new OrganizationName();
         OrganizationName org4 = new OrganizationName();
         org1.setId(105l);
         org1.setOrganizationName("105");
         org2.setId(106l);
         org2.setOrganizationName("106");
         org3.setId(107l);
         org3.setOrganizationName("107");
         org4.setId(108l);
         org4.setOrganizationName("108");
         this.mapper.insert(org1);
         this.mapper.insert(org2);
         this.mapper.insert(org3);
         this.mapper.insert(org4);
         return 1;
     }

重新启动我们的项目访问http://localhost:8080/insert

image.png
没有报错,并且数据成功入库
image.png

读写分离的处理方式 service层事务控制

编写数据源类 MyDruidDataSource

package com.demo.springboot_mybatis.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class MyDruidDataSource  {
    private Logger logger = LoggerFactory.getLogger(MyDruidDataSource.class);  
    
    @Value("${datasource.read.url}")  
    private String dbUrlRead;  
      
    @Value("${datasource.read.username}")  
    private String usernameRead;  
      
    @Value("${datasource.read.password}")  
    private String passwordRead;  
      
    @Value("${datasource.read.driverClassName}")  
    private String driverClassNameRead;  
      
    @Value("${datasource.read.initialSize}")  
    private int initialSizeRead;  
      
    @Value("${datasource.read.minIdle}")  
    private int minIdleRead;  
      
    @Value("${datasource.read.maxActive}")  
    private int maxActiveRead;  
      
    @Value("${datasource.read.maxWait}")  
    private int maxWaitRead;  
      
    @Value("${datasource.read.timeBetweenEvictionRunsMillis}")  
    private int timeBetweenEvictionRunsMillisRead;  
      
    @Value("${datasource.read.minEvictableIdleTimeMillis}")  
    private int minEvictableIdleTimeMillisRead;  
      
    @Value("${datasource.read.validationQuery}")  
    private String validationQueryRead;  
      
    @Value("${datasource.read.testWhileIdle}")  
    private boolean testWhileIdleRead;  
      
    @Value("${datasource.read.testOnBorrow}")  
    private boolean testOnBorrowRead;  
      
    @Value("${datasource.read.testOnReturn}")  
    private boolean testOnReturnRead;  
      
    @Value("${datasource.read.poolPreparedStatements}")  
    private boolean poolPreparedStatementsRead;  
      
    @Value("${datasource.read.filters}")  
    private String filtersRead;  
      
    @Value("${datasource.read.connectionProperties}")  
    private String connectionPropertiesRead;  
    
    
    @Value("${datasource.write.url}")  
    private String dbUrl;  
      
    @Value("${datasource.write.username}")  
    private String username;  
      
    @Value("${datasource.write.password}")  
    private String password;  
      
    @Value("${datasource.write.driverClassName}")  
    private String driverClassName;  
      
    @Value("${datasource.write.initialSize}")  
    private int initialSize;  
      
    @Value("${datasource.write.minIdle}")  
    private int minIdle;  
      
    @Value("${datasource.write.maxActive}")  
    private int maxActive;  
      
    @Value("${datasource.write.maxWait}")  
    private int maxWait;  
      
    @Value("${datasource.write.timeBetweenEvictionRunsMillis}")  
    private int timeBetweenEvictionRunsMillis;  
      
    @Value("${datasource.write.minEvictableIdleTimeMillis}")  
    private int minEvictableIdleTimeMillis;  
      
    @Value("${datasource.write.validationQuery}")  
    private String validationQuery;  
      
    @Value("${datasource.write.testWhileIdle}")  
    private boolean testWhileIdle;  
      
    @Value("${datasource.write.testOnBorrow}")  
    private boolean testOnBorrow;  
      
    @Value("${datasource.write.testOnReturn}")  
    private boolean testOnReturn;  
      
    @Value("${datasource.write.poolPreparedStatements}")  
    private boolean poolPreparedStatements;  
      
    @Value("${datasource.write.filters}")  
    private String filtersWrite;  
      
    @Value("${datasource.write.connectionProperties}")  
    private String connectionProperties;  
      
    @Bean(name="writeDataSource")
    public DataSource writeDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dbUrl);  
        druidDataSource.setUsername(username);  
        druidDataSource.setPassword(password);  
        druidDataSource.setDriverClassName(driverClassName);  
          
        //configuration  
        druidDataSource.setInitialSize(initialSize);  
        druidDataSource.setMinIdle(minIdle);  
        druidDataSource.setMaxActive(maxActive);  
        druidDataSource.setMaxWait(maxWait);  
        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        druidDataSource.setValidationQuery(validationQuery);  
        druidDataSource.setTestWhileIdle(testWhileIdle);  
        druidDataSource.setTestOnBorrow(testOnBorrow);  
        druidDataSource.setTestOnReturn(testOnReturn);  
        druidDataSource.setPoolPreparedStatements(poolPreparedStatements);  
        try {  
            druidDataSource.setFilters(filtersWrite);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        druidDataSource.setConnectionProperties(connectionProperties); 
        return druidDataSource;
    }
    
   
    @Bean(name="readDataSource")
    public DataSource readDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dbUrlRead);  
        druidDataSource.setUsername(usernameRead);  
        druidDataSource.setPassword(passwordRead);  
        druidDataSource.setDriverClassName(driverClassNameRead);  
          
        //configuration  
        druidDataSource.setInitialSize(initialSizeRead);  
        druidDataSource.setMinIdle(minIdleRead);  
        druidDataSource.setMaxActive(maxActiveRead);  
        druidDataSource.setMaxWait(maxWaitRead);  
        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillisRead);  
        druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillisRead);  
        druidDataSource.setValidationQuery(validationQueryRead);  
        druidDataSource.setTestWhileIdle(testWhileIdleRead);  
        druidDataSource.setTestOnBorrow(testOnBorrowRead);  
        druidDataSource.setTestOnReturn(testOnReturnRead);  
        druidDataSource.setPoolPreparedStatements(poolPreparedStatementsRead);  
        try {  
            druidDataSource.setFilters(filtersRead);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        druidDataSource.setConnectionProperties(connectionPropertiesRead);  
        return druidDataSource;
    }
    
}  

编写 mybaties配置类 MybatiesConfig

package com.demo.springboot_mybatis.config;

import java.util.HashMap;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.github.pagehelper.PageHelper;


@Configuration
@Import(MyDruidDataSource.class)
public class MybatiesConfig {
    
    @Value("${spring.datasource.mybatis.base.typeAliases}")
    private String typeAliases;
    
    @Bean
    public AbstractRoutingDataSource roundRobinDataSouceProxy(
            @Qualifier("writeDataSource") DataSource writeDataSource,
            @Qualifier("readDataSource") DataSource readDataSource
            ){
        MyAbstractRoutingDataSoruce  myAbstractRoutingDataSoruce = new MyAbstractRoutingDataSoruce();
        myAbstractRoutingDataSoruce.setDefaultTargetDataSource(writeDataSource);
        HashMap<Object, Object> map = new HashMap<Object,Object>();
        map.put(DataSourceType.write.getType(), writeDataSource);
        map.put(DataSourceType.read.getType(), readDataSource);
        myAbstractRoutingDataSoruce.setTargetDataSources(map);
        return myAbstractRoutingDataSoruce;
    }
    
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(AbstractRoutingDataSource roundRobinDataSouceProxy) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(roundRobinDataSouceProxy);
        if(typeAliases != null  && !"".equals(typeAliases)){
            typeAliases=","+typeAliases;
        }else{
            typeAliases="";
        }
        bean.setTypeAliasesPackage(typeAliases);
        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //配置mapper对应的xml文件在classpath:下
            org.springframework.core.io.Resource[] res = resolver.getResources("classpath:mapper/*.xml");
            if(res!= null && res.length > 0 ){
                 bean.setMapperLocations(res);
            }
        } catch (Exception e) {
        }
        return bean.getObject();
    }
    
    @Bean
    public DataSourceTransactionManager transaction(@Qualifier("writeDataSource") DataSource writeDataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(writeDataSource);
        return dataSourceTransactionManager;
    }
    
}

编写mapperScanner

package com.demo.springboot_mybatis.config;


import java.util.Properties;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * MyBatis扫描接口,使用的tk.mybatis.spring.mapper.MapperScannerConfigurer,如果你不使用通用Mapper,可以改为org.xxx...
 *
 * @author zgf
 * @since 2016-11-14 14:46
 */
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@Configuration
@AutoConfigureAfter(MybatiesConfig.class)
public class MyBatisMapperScannerConfig implements EnvironmentAware {
    
    private RelaxedPropertyResolver propertyResolver;
    @Override
    public void setEnvironment(Environment arg0) {
        this.propertyResolver = new RelaxedPropertyResolver(arg0,
                "");
    } 
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        String mapper = propertyResolver.getProperty("spring.datasource.mybatis.base.mapper");
        if(mapper != null  && !"".equals(mapper)){
            mapper=","+mapper;
        }else{
            mapper="";
        }
        mapperScannerConfigurer.setBasePackage(mapper);
        Properties properties = new Properties();
        properties.setProperty("mappers", "com.demo.util.MyMapper");
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

}

编写数据源类型 DataSourceType

package com.demo.springboot_mybatis.config;

public enum DataSourceType {
    write("write", "写库"), read("read", "读库");
    public String type;
    public String value;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    private DataSourceType(String type, String value) {
        this.type = type;
        this.value = value;
    }

}

编写数据源路由 MyAbstractRoutingDataSoruce

package com.demo.springboot_mybatis.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MyAbstractRoutingDataSoruce extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        String datatype = DataSourceHolder.threadLocal.get();
        if(datatype == null){
            return DataSourceType.write.getType();
        }
        return datatype;
    }
    
    
    

}

编写数据源控制类 DataSourceHolder

package com.demo.springboot_mybatis.config;

public class DataSourceHolder {
     public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
     
     public static void read(){
         threadLocal.set(DataSourceType.read.getType());
     }
     
     public static void write(){
         threadLocal.set(DataSourceType.write.getType());
     }
     
     
     public static String getType(){
         return threadLocal.get();
     }
    
    
}

编写aop 切换数据源 DataSourceAop

package com.demo.springboot_mybatis.config;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataSourceAop {
    @Before("execution(* com.demo.springboot_mybatis.service.*.read*(..))")
    public void read(){
        DataSourceHolder.read();
    }
    @Before("execution(* com.demo.springboot_mybatis.service.*.insert*(..))")
    public void write(){
        DataSourceHolder.write();
    }
}

编写通用service AbstractBaseService

package com.demo.springboot_mybatis.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.demo.util.MyMapper;

import tk.mybatis.mapper.entity.Example;

public class AbstractBaseService<CommonMapper extends MyMapper<T>, T extends Object>  {

     @Autowired  
     protected CommonMapper mapper; 
    
    public List<T> selectAll() {
        return mapper.selectAll();
    }
    
    public T selectByPrimarikey(Object key) {
        return mapper.selectByPrimaryKey(key);
    }
    
    public int updateByPrimarikey(T t) {
        return mapper.updateByPrimaryKeySelective(t);
    }
    
    public int updateByExample(T t,Example example) {
        return mapper.updateByExampleSelective(t, example);
    }
    
    public int insert(T t) {
        return mapper.insert(t);
    }
    
    public int insertList(List<T> t) {
        return mapper.insertList(t);
    }
    
    public int deleteByPrimarikey(Object key) {
        return mapper.deleteByPrimaryKey(key);
    }
    
    public int deleteByExample(Example example) {
        return mapper.deleteByExample(example);
    }
    
    public List<T> selectByExample(Example example) {
        return mapper.selectByExample(example);
    }
}

编写mapper model service
OrganizationName OrganizationNameMapper OrganizationNameService

package com.demo.springboot_mybatis.model;

import java.io.Serializable;

public class OrganizationName implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Long id ;  //机构名称id
    private String  organizationName; //机构名称
    private Long parent_id; //父机构id
    private Integer organizationType; //机构类型
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getOrganizationName() {
        return organizationName;
    }
    public void setOrganizationName(String organizationName) {
        this.organizationName = organizationName;
    }
    
    public Long getParent_id() {
        return parent_id;
    }
    public void setParent_id(Long parent_id) {
        this.parent_id = parent_id;
    }
    public Integer getOrganizationType() {
        return organizationType;
    }
    public void setOrganizationType(Integer organizationType) {
        this.organizationType = organizationType;
    }
    
}


package com.demo.springboot_mybatis.mapper;

import com.demo.springboot_mybatis.model.OrganizationName;
import com.demo.util.MyMapper;

public interface OrganizationNameMapper extends MyMapper<OrganizationName>{
}


package com.demo.springboot_mybatis.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.springboot_mybatis.config.AbstractBaseService;
import com.demo.springboot_mybatis.mapper.OrganizationNameMapper;
import com.demo.springboot_mybatis.model.OrganizationName;

@Service
public class OrganizationNameService 
extends AbstractBaseService<OrganizationNameMapper, OrganizationName> {
     @Transactional
     public int insertOrganizationName(){
         this.selectAll();
         
         OrganizationName org1 = new OrganizationName();
         OrganizationName org2 = new OrganizationName();
         OrganizationName org3 = new OrganizationName();
         OrganizationName org4 = new OrganizationName();
         org1.setOrganizationName("105");
         org2.setOrganizationName("106");
         org3.setOrganizationName("107");
         org4.setOrganizationName("108");
         this.mapper.insert(org1);
         this.mapper.insert(org2);
         this.mapper.insert(org3);
         this.mapper.insert(org4);
         return 1;
     }
     
     @Transactional
     public int readOrganizationName(){
         OrganizationName org1 = new OrganizationName();
         OrganizationName org2 = new OrganizationName();
         OrganizationName org3 = new OrganizationName();
         OrganizationName org4 = new OrganizationName();
         org1.setOrganizationName("105");
         org2.setOrganizationName("106");
         org3.setOrganizationName("107");
         org4.setOrganizationName("108");
         this.mapper.insert(org1);
         this.mapper.insert(org2);
         this.mapper.insert(org3);
         this.mapper.insert(org4);
         return 1;
     }
}

编写controlelr进行测试

package com.demo.springboot_mybatis.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.springboot_mybatis.service.OrganizationNameService;



@RestController
public class RestHelloController {
    
    @Autowired
    OrganizationNameService organizationNameService;
    
    @RequestMapping("/insert")
    public String insert(HttpServletRequest request) throws Exception{
        organizationNameService.insertOrganizationName();
//      organizationNameService.readOrganizationName();
        return "";
    } 
}

重新启动我们的项目访问http://localhost:8080/insert

相关文章

网友评论

      本文标题:spring boot 学习(事务处理)

      本文链接:https://www.haomeiwen.com/subject/csfnvxtx.html