Because I have a lot of data sources very dynamically, I'd like to find a way to manage spring transation programmatically, create data sources programmatically. In the code below, I will create table t1 twice designedly to make an exception thrown, transation will be rollback. But when I run the code, table "t1" will be created, and "t1name" will be inserted into column "name". Why rollback doesn't work in my case?
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);
}
}