Spring编程式事务管理的简单实现

一个很简单的Spring JDBC 编程式事务的简单实现,代码逻辑较简单,希望有可能帮助初学的同学。本例使用mysql8.0,在db3数据库下有个student表,内含两个属性,id与name。

Spring编程式事务管理的简单实现_第1张图片

Spring编程式事务管理的简单实现_第2张图片



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


public class JdbcTemplateTest {


      public static void main(String[] args) { //加载配置文件

        ApplicationContext applicationContext =new ClassPathXmlApplicationContext("Beans.xml");

        //获取jdbcTemplate实例
        JdbcTemplate jdbcTemplate=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");

        TransactionDefinition def = new DefaultTransactionDefinition();  // 定义事务属性

          DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) applicationContext.getBean("transactionManager");

        TransactionStatus status = transactionManager.getTransaction(def);

        

        try{
            jdbcTemplate.execute("insert into students values(2,\"zhangsan\");");
            jdbcTemplate.execute("insert into students values(2,\"zhangsan\");");
            //id为primary key,不能重复,否则会报错,事务回滚,也就是这个人不能加入数据库
            transactionManager.commit(status);
        }
        catch(Exception e){
            transactionManager.rollback(status);

        }


          
      }




}

 



    
    
        
        
        
        
        
        
        
        
    

    
    
        
        
    

    

    
        
    

 

 

你可能感兴趣的:(Spring编程式事务管理的简单实现)