- package org.springframework.transaction.support;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.beans.factory.InitializingBean;
- import org.springframework.transaction.PlatformTransactionManager;
- import org.springframework.transaction.TransactionDefinition;
- import org.springframework.transaction.TransactionException;
- import org.springframework.transaction.TransactionStatus;
- import org.springframework.transaction.TransactionSystemException;
- public class TransactionTemplate extends DefaultTransactionDefinition
- implements TransactionOperations, InitializingBean {
- /** Logger available to subclasses */
- protected final Log logger = LogFactory.getLog(getClass());
- private PlatformTransactionManager transactionManager;
- public TransactionTemplate() {
- }
- sactionTemplate(PlatformTransactionManager transactionManager) {
- this.transactionManager = transactionManager;
- }
- public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
- super(transactionDefinition);
- this.transactionManager = transactionManager;
- }
- /**
- * Set the transaction management strategy to be used.
- */
- public void setTransactionManager(PlatformTransactionManager transactionManager) {
- this.transactionManager = transactionManager;
- }
- /**
- * Return the transaction management strategy to be used.
- */
- public PlatformTransactionManager getTransactionManager() {
- return this.transactionManager;
- }
- public void afterPropertiesSet() {
- if (this.transactionManager == null) {
- throw new IllegalArgumentException("Property 'transactionManager' is required");
- }
- }
- public Object execute(TransactionCallback action) throws TransactionException {
- if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
- return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
- }
- else {
- TransactionStatus status = this.transactionManager.getTransaction(this);
- Object result = null;
- try {
- result = action.doInTransaction(status);
- }
- catch (RuntimeException ex) {
- // Transactional code threw application exception -> rollback
- rollbackOnException(status, ex);
- throw ex;
- }
- catch (Error err) {
- // Transactional code threw error -> rollback
- rollbackOnException(status, err);
- throw err;
- }
- this.transactionManager.commit(status);
- return result;
- }
- }
- private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
- logger.debug("Initiating transaction rollback on application exception", ex);
- try {
- this.transactionManager.rollback(status);
- }
- catch (TransactionSystemException ex2) {
- logger.error("Application exception overridden by rollback exception", ex);
- ex2.initApplicationException(ex);
- throw ex2;
- }
- catch (RuntimeException ex2) {
- logger.error("Application exception overridden by rollback exception", ex);
- throw ex2;
- }
- catch (Error err) {
- logger.error("Application exception overridden by rollback error", ex);
- throw err;
- }
- }
- }<pre></pre>
- <pre></pre>
- <p> </p>
- <p>1 <span style="font-family:宋体">、使用<span lang="EN-US">TransactionTemplate</span>进行事务处理(<span lang="EN-US">Spring</span>进行<span lang="EN-US">commit</span>和<span lang="EN-US">rollback</span>)</span></p>
- <p><span style="font-size:24px"><span style="font-family:宋体"> <span style="font-family:宋体">
- (</span> <span lang="EN-US">1</span> <span style="font-family:宋体">)使用事务处理的类</span>
- </span></span></p>
- <pre class="Java" name="code">import javax.sql.DataSource;
- import org.springframework.jdbc.core.*;
- import org.springframework.transaction.*;
- import org.springframework.dao.*;
- public class bookDAO{
- private DataSource dataSource;// 依赖注入 dataSource ,管理数据库
- private PlatformTransationManager transactionManager;// 依赖注入管理事务
- public void setDataSource(DataSource dataSource){
- this.dataSource=dataSource;
- }
- public void setTransactionManager(PlatformTransationManager transactionManager){
- this. transactionManager= transactionManager;
- }
- public int create(String msg){
- TransactionTemplate transactionTemplate=new TransactionTemplate(transactionManager);
- // 调用 transactionTemplate 的 execute 方法进行事务管理
- Object result= transactionTemplate.execute (
- // 这是一个回调函数,实现了 TransactionCallback 接口的 doInTransaction 方法,就是在这个方法里写数据库新增数据的操作
- new TransactionCallback()
- {
- public Object doInTransaction(TransactionStatus status)
- {
- // 数据库操作代码
- return resultObject;
- }
- }
- )
- }
- }
- <pre></pre>
- <pre></pre>
- <p> </p>
- <p><span lang="EN-US"><span style="font-family:宋体">(</span> <span lang="EN-US">2</span>
- <span style="font-family:宋体">)配置文件</span> </span></p>
- <p><span lang="EN-US"> </span></p>
- <pre class="XML" name="code">
- <beans>
- <!— 设 定dataSource à
- <bean id="”dataSource”" class="”org.springframework.jdbc.datasource.DriverManagerDataSource”">
- <!— 使用SQL Server 数 据 库 à
- <property name="”driverClassName”">
- <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
- <property name="”url”">
- <value>jdbc:Microsoft:sqlserver://localhost:1433/stdb</value>
- </property>
- <property name="”name”">
- <value>admin</value>
- </property>
- <property name="”msg”">
- <value>admin</value>
- </property>
- </property></bean>
- <!— 设定 transactionManager à
- <bean id="”transactionManager”" class="”org.springframework.jdbc.datasource.DataSourceTransactionManager”">
- <property name="”dataSource”">
- <ref bean="”dataSource”/">
- </ref></property>
- </bean>
- <!— 示例中 DAO-->
- <bean id="”bookDAO”" class="”com.bookDAO”">
- <property name="”dataSource”">
- <ref bean="”dataSource”/">
- </ref></property>
- <property name="”transactionManager”">
- <ref bean="”transactionManager”">
- </ref></property>
- </bean>
- </beans>
- <pre></pre>
- <pre></pre>
- <p>二,<span style="font-family:宋体">如果不想返回结果(</span> <span lang="EN-US">resultObject</span>
- <span style="font-family:宋体">),则可以用</span> <span lang="EN-US">TransactionCallbackWithoutResult</span>
- <span style="font-family:宋体">来实现</span> <span lang="EN-US">TransactionCallback</span>
- <span style="font-family:宋体">接口,代码如下:</span> </p>
- <p></p>
- <pre class="Java" name="code"> new TransactionCallback WithoutResult ()
- {
- public Object doInTransaction WithoutResult (TransactionStatus status)
- {
- // 数据库操作代码
- }
- }
- <pre></pre>
- <pre></pre>
- <p> </p>
- <p>三,</p>
- <pre class="Java" name="code">import javax.sql.DataSource;
- import org.springframework.jdbc.core.*;
- import org.springframework.transaction.*;
- import org.springframework.dao.*;
- public class bookDAO{
- private DataSource dataSource;// 依赖注入 dataSource ,管理数据库
- private PlatformTransationManager transactionManager;// 依赖注入管理事务
- public void setDataSource(DataSource dataSource){
- this.dataSource=dataSource;
- }
- public void setTransactionManager(PlatformTransationManager transactionManager){
- this. transactionManager= transactionManager;
- }
- public int create(String msg){
- DefaultTransactionDefinition def =new DefaultTransactionDefinition();
- TransactionStatus status=transactionManager.getTransaction(def);
- try
- {
- JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
- jdbcTemplate.update(“INSERT INTO book VALUES(1,’gf’,’Mastering Spring’)”);
- }
- catch(DataAccessException ex)
- {
- transactionzManager.rollback(status);
- throw ex;
- }
- finally
- {
- transactionManager.commit(status);
- }
- }
- }
- <pre></pre>
- <pre></pre>
- <p> </p>
- </pre></pre></pre></pre>