在Spring中数据库事务是通过PlatformTransactionManager进行管理的,jdbcTemplate是不能支持事务的,而能够支持事务的是org.springframework.transaction.support.TransactionTemplate模板,它是Spring所提供的事务管理器的模板
•事务的创建、提交和回滚是通过PlatformTransactionManager接口来完成的。
•当事务产生异常时会回滚事务,在默认的实现中所有的异常都会回滚。我们可以通过配置去修改在某些异常发生时回滚或者不回滚事务。
•当无异常时,会提交事务。
支持JTA事务,常用的是DataSourceTransactionManager,它继承抽象事务管理器AbstractPlatformTransactionManager,而AbstractPlatformTransactionManager又实现了PlatformTransactionManager。这样Spring就可以如同源码中看到的那样使用PlatformTransactionManager接口的方法,创建、提交或者回滚事务了。
配置事务管理器
MyBatis框架用得最多的事务管理器是DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager),因此下面将以此例进行讲解。如果使用的持久框架是Hibernate,那么你就要用到spring-orm包org.springframework.orm.hibernate4.HibernateTransactionManager了。它们大同小异,一般而言我们在使用时,还会加入XML的事务命名空间。下面配置一个事务管理器
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
这里先引入了XML的命名空间,然后定义了数据库连接池,于是使用了DataSourceTransac