手动开启事务/保存点/隐式发出commit的语句

手动开启事务/保存点/隐式发出commit的语句

1.手动开启事务
	@Autowired
	DataSourceTransactionManager dataSourceTransactionManager;
	@Autowired
	TransactionDefinition transactionDefinition;
	TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);//transactionDefinition可以设置事务类型等
	等价于TransactionStatus transactionStatus =TransactionAspectSupport.currentTransactionStatus();//获取@Transactional方式的当前事务
	手动提交事务
	dataSourceTransactionManager.commit(transactionStatus);//提交
	手动回滚事务
	dataSourceTransactionManager.rollback(transactionStatus);//最好是放在catch 里面,防止程序异常而事务一直卡在哪里未提交
	
	
2.保存点
	官网语法
		SAVEPOINT identifier
		ROLLBACK [WORK] TO [SAVEPOINT] identifier
		RELEASE SAVEPOINT identifier
	测试
		mysql> BEGIN;
		mysql> INSERT INTO T2 VALUES(100);
		mysql> SAVEPOINT svp1;
		mysql> INSERT INTO T2 VALUES(200);
		mysql> ROLLBACK TO SAVEPOINT svp1;
		mysql> RELEASE SAVEPOINT svp1;
		mysql> COMMIT; 
		mysql> SELECT * FROM T2;
		+------+
		| ID   |
		+------+
		|  100 |
		+------+
		1 row in set (0.00 sec)

	1.注意的问题是保存点只能回滚不能提交保存点
	2.注意Savepoint1中如果有Savepoint2嵌套 则回滚会把Savepoint2也回滚
	3.这种方式又延迟需要等到方法完成才能起作用(如果嵌套有其他逻辑最终可能会导致失败)
	Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();//创建Savepoint
	TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);//回滚指定的Savepoint
	TransactionAspectSupport.currentTransactionStatus().releaseSavepoint(savepoint);//释放指定的Savepoint
3.隐式发出commit的语句
	1.DDL语句
	2.隐式地使用或者修改mysql数据库的语句  ALTER USER, CREATE USER, DROP USER, GRANT, RENAME USER, REVOKE, SET PASSWORD
	3.事务控制和锁语句,比如BEGIN,START TRANSACTION,  LOCK/UNLOCK TABLES, SET autocommit = 1(原来不是1)

你可能感兴趣的:(java)