//xml文件配置spring的情况下:
applicationContext.xml:
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
//----
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
DataSourceTransactionManagertransactionManager =(DataSourceTransactionManager)ctx
.getBean("txManager");
DefaultTransactionDefinitiondef=newDefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别,开启新事务,这样会比较安全些。
TransactionStatusstatus =transactionManager.getTransaction(def);// 获得事务状态
try{
//逻辑代码,可以写上你的逻辑处理代码
transactionManager.commit(status);
}catch(Exceptione){
transactionManager.rollback(status);
}
//代码设置数据源的情况下:
@Autowired
DataSourceTransactionManager dataSourceTransactionManager;
DefaultTransactionDefinition def;
{
def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
//开启事务
TransactionStatus transaction1 = dataSourceTransactionManager.getTransaction(def);
dataSourceTransactionManager.commit(transaction1);
dataSourceTransactionManager.commit(transaction1);