Spring的编程式事务管理(transactionTemplate)学习记录【简单易懂】

描述:

主要是运用的是spring-tx提供的摸板类。

公司要求写个windows下的脚本来执行对一些XML文件内容的解析与插入。编码这部分:主要是调用java的main方法来进行程序操作的,下面我来说明下对编程式事务管理的一些详细配置。

参考:

https://blog.csdn.net/zhuxinquan61/article/details/71075051

  • spring的配置文件


    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
    http://www.springframework.org/schema/jee   
    http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    
    

    
    
        
        
        
        
    

    
    
        
        
    

    
    
   
       
       
   

    
    

       
        

       
        
     
    
    
    

        
    
 

    
    
    

        
    

  • main方法

//下面代码大家应该熟悉吧,读取Spring的配置文件,通过applicationContext来获取bean

ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");    
XxxServiceImpl xxxServiceImpl= (XxxServiceImpl) applicationContext.getBean("xxxServiceImpl");

  • service中的代码

在配置文件中,已经声明了serviceImpl的bean,并把sqlSession与transactionTemplate 通过set方法注入到里面,所以直接在service中获取dao层的mapper来执行插入就可以了。

    private TransactionTemplate transactionTemplate;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession = null;
    

    //为了set方法注入
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

   //为了set方法注入

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
    
    @Override
    public void insertBatch( final XXX xxx,  final List list) throws Exception {
        sqlSession = sqlSessionFactory.openSession();
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {       
                sqlSession.getMapper(XXXMapper.class).inserBatch(list);           
                sqlSession.getMapper(XXXMapper.class).insert(xxx);                
            }
        });

    }

这样就可以简单的实现事务管理了。

大家也看出来了,这些东西都是比较适合新手的 ,因为本人是新手,所以也写不出来什么高端的东西,只是把这么简单的东西,自己遇到的东西来记录一下,如果您看到这里能有些启发,就是我的荣幸了。

你可能感兴趣的:(spring)