抛出异常时Spring编程事务管理不会回滚

时间:2016-04-20 14:42:24

标签: spring transactions

因为我非常动态地拥有大量数据源,所以我想找到一种以编程方式管理Spring转换的方法,以编程方式创建数据源。 在下面的代码中,我将创建表t1两次,以便抛出异常,transation将是回滚。但是当我运行代码时,表" t1"将被创建," t1name"将被插入列" name"。 为什么回滚在我的情况下不起作用?

public static void main(String[] args) {
    DataSource dataSource = new DriverManagerDataSource("jdbc:mysql://localhost:3306/abc", "root", "root");

    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); 
    TransactionDefinition def = new DefaultTransactionDefinition();
    TransactionStatus status = transactionManager.getTransaction(def);
    JdbcTemplate jdbc = new JdbcTemplate(dataSource);
    String sql = null;

    try {       
        sql = "create table t1 (`name` varchar(30))";
        PreparedStatementCreatorFactory statementCreatorFactory = new PreparedStatementCreatorFactory(sql);
        PreparedStatementCreator creator = statementCreatorFactory.newPreparedStatementCreator(new Object[] {});
        jdbc.update(creator);       

        sql = "INSERT INTO `t1` (`name`) VALUES ('t1name')";    
        statementCreatorFactory = new PreparedStatementCreatorFactory(sql);
        statementCreatorFactory.setReturnGeneratedKeys(true);
        creator = statementCreatorFactory.newPreparedStatementCreator(new Object[] {});
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbc.update(creator, keyHolder);

        sql = "create table t1 (`name` varchar(30))";       // table exists already, will cause rollback. 
        statementCreatorFactory = new PreparedStatementCreatorFactory(sql);
        creator = statementCreatorFactory.newPreparedStatementCreator(new Object[] {});
        jdbc.update(creator);                   

        transactionManager.commit(status);
    } catch (Exception e) {
        e.printStackTrace();
        transactionManager.rollback(status);
    }
}

0 个答案:

没有答案