spring入门详细教程(五)

举报
经典鸡翅 发表于 2022/02/17 22:53:07 2022/02/17
【摘要】 前言 本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇。链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/10165538.html Spring入门详细教程(二) https://www.cnblog...

前言

本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇。链接如下:

Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/10165538.html

Spring入门详细教程(二) https://www.cnblogs.com/jichi/p/10176601.html

Spring入门详细教程(三) https://www.cnblogs.com/jichi/p/10177004.html

Spring入门详细教程(四) https://www.cnblogs.com/jichi/p/10211475.html

本篇主要讲解spring的事务处理。

一、什么是事务

事务用白话来说比较好理解,我们举个例子。比如说你做两件事要达成一个目的。其中有一件事失败,你就相当于没做。如果两件事都成功,这件事你才算做的成功。用官方话来解释,就是事务是逻辑上的一组操作,组成这组操作的各个逻辑单元,要么一起成功,要么一起失败。

二、事务的特性

了解了事务的概念,我们就可以了解事务的特性了。

事务有四大特性:原子性,一致性,隔离性,持久性。

原子性:强调事务的不可分割。

一致性:事务的执行的前后数据的完整性保持一致。

隔离性:一个事务执行的过程中,不应受到其他事务的干扰。

持久性:事务一旦结束,数据就持久到数据库。

三、事务的并发问题

事务三大问题,脏读,幻读,不可重复读。

脏读:一个事务读到了另一个事务的未提交的数据。

不可重复读:一个事务读到了另一个事务已经提交的update的数据导致多次查询结果不一致。

虚幻读:一个事务读到了另一个事务已经提交的insert的数据导致多次查询结果不一致。

四、事务并发问题的解决:事务隔离级别

1、未提交读:脏读,不可重复读,虚幻读都有可能发生。

2、已提交读:避免脏读。不可重复读和虚幻读都可能发生。

3、可重复读:避免脏读和不可重复读。虚幻读可能发生。

4、串行化:避免以上所有的读问题。

事务的隔离级别越高,性能会降的越低。其实就是牺牲性能来提高准确性。在实际中,一般选取中间的隔离级别。

mysql默认隔离级别:可重复读。

oracle默认隔离级别:已提交读。

五、spring封装事务

首先spring封装了我们需要进行的事务操作。事务操作是什么呢。比如说我们首先需要打开事务,进行操作后,提交事务。如果发生错误,回滚事务,如果中途未发生错误,则事务进行提交。如果spring没有对事务进行封装,我们需要没进行一次操作都重新写事务的处理代码。spring封装后,事务代码被封装,我们不用一遍遍的重复编写代码,配置好后,不用书写事务代码。接下来我们了解几个spring中事务的相关概念。

1、PlatformTransactionManager平台事务管理器

在不同的平台,操作代码的事务各不相同,spring为我们提供了一个接口。这个接口就是PlatformTransactionManager。

我们可以看一下里面的源码。提供了一个获得事务的方法,一个提交事务的方法以及一个回滚事务的方法。此处贴一下源码


    
  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.transaction;
  17. /**
  18. * This is the central interface in Spring's transaction infrastructure.
  19. * Applications can use this directly, but it is not primarily meant as API:
  20. * Typically, applications will work with either TransactionTemplate or
  21. * declarative transaction demarcation through AOP.
  22. *
  23. * <p>For implementors, it is recommended to derive from the provided
  24. * {@link org.springframework.transaction.support.AbstractPlatformTransactionManager}
  25. * class, which pre-implements the defined propagation behavior and takes care
  26. * of transaction synchronization handling. Subclasses have to implement
  27. * template methods for specific states of the underlying transaction,
  28. * for example: begin, suspend, resume, commit.
  29. *
  30. * <p>The default implementations of this strategy interface are
  31. * {@link org.springframework.transaction.jta.JtaTransactionManager} and
  32. * {@link org.springframework.jdbc.datasource.DataSourceTransactionManager},
  33. * which can serve as an implementation guide for other transaction strategies.
  34. *
  35. * @author Rod Johnson
  36. * @author Juergen Hoeller
  37. * @since 16.05.2003
  38. * @see org.springframework.transaction.support.TransactionTemplate
  39. * @see org.springframework.transaction.interceptor.TransactionInterceptor
  40. * @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean
  41. */
  42. public interface PlatformTransactionManager {
  43. /**
  44. * Return a currently active transaction or create a new one, according to
  45. * the specified propagation behavior.
  46. * <p>Note that parameters like isolation level or timeout will only be applied
  47. * to new transactions, and thus be ignored when participating in active ones.
  48. * <p>Furthermore, not all transaction definition settings will be supported
  49. * by every transaction manager: A proper transaction manager implementation
  50. * should throw an exception when unsupported settings are encountered.
  51. * <p>An exception to the above rule is the read-only flag, which should be
  52. * ignored if no explicit read-only mode is supported. Essentially, the
  53. * read-only flag is just a hint for potential optimization.
  54. * @param definition TransactionDefinition instance (can be {@code null} for defaults),
  55. * describing propagation behavior, isolation level, timeout etc.
  56. * @return transaction status object representing the new or current transaction
  57. * @throws TransactionException in case of lookup, creation, or system errors
  58. * @throws IllegalTransactionStateException if the given transaction definition
  59. * cannot be executed (for example, if a currently active transaction is in
  60. * conflict with the specified propagation behavior)
  61. * @see TransactionDefinition#getPropagationBehavior
  62. * @see TransactionDefinition#getIsolationLevel
  63. * @see TransactionDefinition#getTimeout
  64. * @see TransactionDefinition#isReadOnly
  65. */
  66. TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;
  67. /**
  68. * Commit the given transaction, with regard to its status. If the transaction
  69. * has been marked rollback-only programmatically, perform a rollback.
  70. * <p>If the transaction wasn't a new one, omit the commit for proper
  71. * participation in the surrounding transaction. If a previous transaction
  72. * has been suspended to be able to create a new one, resume the previous
  73. * transaction after committing the new one.
  74. * <p>Note that when the commit call completes, no matter if normally or
  75. * throwing an exception, the transaction must be fully completed and
  76. * cleaned up. No rollback call should be expected in such a case.
  77. * <p>If this method throws an exception other than a TransactionException,
  78. * then some before-commit error caused the commit attempt to fail. For
  79. * example, an O/R Mapping tool might have tried to flush changes to the
  80. * database right before commit, with the resulting DataAccessException
  81. * causing the transaction to fail. The original exception will be
  82. * propagated to the caller of this commit method in such a case.
  83. * @param status object returned by the {@code getTransaction} method
  84. * @throws UnexpectedRollbackException in case of an unexpected rollback
  85. * that the transaction coordinator initiated
  86. * @throws HeuristicCompletionException in case of a transaction failure
  87. * caused by a heuristic decision on the side of the transaction coordinator
  88. * @throws TransactionSystemException in case of commit or system errors
  89. * (typically caused by fundamental resource failures)
  90. * @throws IllegalTransactionStateException if the given transaction
  91. * is already completed (that is, committed or rolled back)
  92. * @see TransactionStatus#setRollbackOnly
  93. */
  94. void commit(TransactionStatus status) throws TransactionException;
  95. /**
  96. * Perform a rollback of the given transaction.
  97. * <p>If the transaction wasn't a new one, just set it rollback-only for proper
  98. * participation in the surrounding transaction. If a previous transaction
  99. * has been suspended to be able to create a new one, resume the previous
  100. * transaction after rolling back the new one.
  101. * <p><b>Do not call rollback on a transaction if commit threw an exception.</b>
  102. * The transaction will already have been completed and cleaned up when commit
  103. * returns, even in case of a commit exception. Consequently, a rollback call
  104. * after commit failure will lead to an IllegalTransactionStateException.
  105. * @param status object returned by the {@code getTransaction} method
  106. * @throws TransactionSystemException in case of rollback or system errors
  107. * (typically caused by fundamental resource failures)
  108. * @throws IllegalTransactionStateException if the given transaction
  109. * is already completed (that is, committed or rolled back)
  110. */
  111. void rollback(TransactionStatus status) throws TransactionException;
  112. }

我们通过查看接口发现AbstractPlatformTransactionManager实现了这一接口。其中提供了一些方法。继续查看谁继承了该抽象类。

发现有两个:DataSourceTransactionManager与HibernateTransitionmanager。

DataSourceTransactionManager:这一事务管理类,在用spring的jdbc以及mybaties进行操作事务的时候使用。

HibernateTransitionmanager:在用hiberante进行操作事务的时候使用。

2、TransactionDefinition事务定义信息

主要记录了事务的定义信息相关。

记录了事务的隔离级别,事务传播行为,超时信息,只读信息的基本信息。此处可以看一下源码感受一下,这里面的一些信息,后面会讲解


    
  1. /*
  2. * Copyright 2002-2015 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.transaction;
  17. import java.sql.Connection;
  18. /**
  19. * Interface that defines Spring-compliant transaction properties.
  20. * Based on the propagation behavior definitions analogous to EJB CMT attributes.
  21. *
  22. * <p>Note that isolation level and timeout settings will not get applied unless
  23. * an actual new transaction gets started. As only {@link #PROPAGATION_REQUIRED},
  24. * {@link #PROPAGATION_REQUIRES_NEW} and {@link #PROPAGATION_NESTED} can cause
  25. * that, it usually doesn't make sense to specify those settings in other cases.
  26. * Furthermore, be aware that not all transaction managers will support those
  27. * advanced features and thus might throw corresponding exceptions when given
  28. * non-default values.
  29. *
  30. * <p>The {@link #isReadOnly() read-only flag} applies to any transaction context,
  31. * whether backed by an actual resource transaction or operating non-transactionally
  32. * at the resource level. In the latter case, the flag will only apply to managed
  33. * resources within the application, such as a Hibernate {@code Session}.
  34. *
  35. * @author Juergen Hoeller
  36. * @since 08.05.2003
  37. * @see PlatformTransactionManager#getTransaction(TransactionDefinition)
  38. * @see org.springframework.transaction.support.DefaultTransactionDefinition
  39. * @see org.springframework.transaction.interceptor.TransactionAttribute
  40. */
  41. public interface TransactionDefinition {
  42. /**
  43. * Support a current transaction; create a new one if none exists.
  44. * Analogous to the EJB transaction attribute of the same name.
  45. * <p>This is typically the default setting of a transaction definition,
  46. * and typically defines a transaction synchronization scope.
  47. */
  48. int PROPAGATION_REQUIRED = 0;
  49. /**
  50. * Support a current transaction; execute non-transactionally if none exists.
  51. * Analogous to the EJB transaction attribute of the same name.
  52. * <p><b>NOTE:</b> For transaction managers with transaction synchronization,
  53. * {@code PROPAGATION_SUPPORTS} is slightly different from no transaction
  54. * at all, as it defines a transaction scope that synchronization might apply to.
  55. * As a consequence, the same resources (a JDBC {@code Connection}, a
  56. * Hibernate {@code Session}, etc) will be shared for the entire specified
  57. * scope. Note that the exact behavior depends on the actual synchronization
  58. * configuration of the transaction manager!
  59. * <p>In general, use {@code PROPAGATION_SUPPORTS} with care! In particular, do
  60. * not rely on {@code PROPAGATION_REQUIRED} or {@code PROPAGATION_REQUIRES_NEW}
  61. * <i>within</i> a {@code PROPAGATION_SUPPORTS} scope (which may lead to
  62. * synchronization conflicts at runtime). If such nesting is unavoidable, make sure
  63. * to configure your transaction manager appropriately (typically switching to
  64. * "synchronization on actual transaction").
  65. * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization
  66. * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION
  67. */
  68. int PROPAGATION_SUPPORTS = 1;
  69. /**
  70. * Support a current transaction; throw an exception if no current transaction
  71. * exists. Analogous to the EJB transaction attribute of the same name.
  72. * <p>Note that transaction synchronization within a {@code PROPAGATION_MANDATORY}
  73. * scope will always be driven by the surrounding transaction.
  74. */
  75. int PROPAGATION_MANDATORY = 2;
  76. /**
  77. * Create a new transaction, suspending the current transaction if one exists.
  78. * Analogous to the EJB transaction attribute of the same name.
  79. * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
  80. * on all transaction managers. This in particular applies to
  81. * {@link org.springframework.transaction.jta.JtaTransactionManager},
  82. * which requires the {@code javax.transaction.TransactionManager} to be
  83. * made available it to it (which is server-specific in standard Java EE).
  84. * <p>A {@code PROPAGATION_REQUIRES_NEW} scope always defines its own
  85. * transaction synchronizations. Existing synchronizations will be suspended
  86. * and resumed appropriately.
  87. * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
  88. */
  89. int PROPAGATION_REQUIRES_NEW = 3;
  90. /**
  91. * Do not support a current transaction; rather always execute non-transactionally.
  92. * Analogous to the EJB transaction attribute of the same name.
  93. * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
  94. * on all transaction managers. This in particular applies to
  95. * {@link org.springframework.transaction.jta.JtaTransactionManager},
  96. * which requires the {@code javax.transaction.TransactionManager} to be
  97. * made available it to it (which is server-specific in standard Java EE).
  98. * <p>Note that transaction synchronization is <i>not</i> available within a
  99. * {@code PROPAGATION_NOT_SUPPORTED} scope. Existing synchronizations
  100. * will be suspended and resumed appropriately.
  101. * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
  102. */
  103. int PROPAGATION_NOT_SUPPORTED = 4;
  104. /**
  105. * Do not support a current transaction; throw an exception if a current transaction
  106. * exists. Analogous to the EJB transaction attribute of the same name.
  107. * <p>Note that transaction synchronization is <i>not</i> available within a
  108. * {@code PROPAGATION_NEVER} scope.
  109. */
  110. int PROPAGATION_NEVER = 5;
  111. /**
  112. * Execute within a nested transaction if a current transaction exists,
  113. * behave like {@link #PROPAGATION_REQUIRED} else. There is no analogous
  114. * feature in EJB.
  115. * <p><b>NOTE:</b> Actual creation of a nested transaction will only work on
  116. * specific transaction managers. Out of the box, this only applies to the JDBC
  117. * {@link org.springframework.jdbc.datasource.DataSourceTransactionManager}
  118. * when working on a JDBC 3.0 driver. Some JTA providers might support
  119. * nested transactions as well.
  120. * @see org.springframework.jdbc.datasource.DataSourceTransactionManager
  121. */
  122. int PROPAGATION_NESTED = 6;
  123. /**
  124. * Use the default isolation level of the underlying datastore.
  125. * All other levels correspond to the JDBC isolation levels.
  126. * @see java.sql.Connection
  127. */
  128. int ISOLATION_DEFAULT = -1;
  129. /**
  130. * Indicates that dirty reads, non-repeatable reads and phantom reads
  131. * can occur.
  132. * <p>This level allows a row changed by one transaction to be read by another
  133. * transaction before any changes in that row have been committed (a "dirty read").
  134. * If any of the changes are rolled back, the second transaction will have
  135. * retrieved an invalid row.
  136. * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED
  137. */
  138. int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;
  139. /**
  140. * Indicates that dirty reads are prevented; non-repeatable reads and
  141. * phantom reads can occur.
  142. * <p>This level only prohibits a transaction from reading a row
  143. * with uncommitted changes in it.
  144. * @see java.sql.Connection#TRANSACTION_READ_COMMITTED
  145. */
  146. int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;
  147. /**
  148. * Indicates that dirty reads and non-repeatable reads are prevented;
  149. * phantom reads can occur.
  150. * <p>This level prohibits a transaction from reading a row with uncommitted changes
  151. * in it, and it also prohibits the situation where one transaction reads a row,
  152. * a second transaction alters the row, and the first transaction re-reads the row,
  153. * getting different values the second time (a "non-repeatable read").
  154. * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ
  155. */
  156. int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;
  157. /**
  158. * Indicates that dirty reads, non-repeatable reads and phantom reads
  159. * are prevented.
  160. * <p>This level includes the prohibitions in {@link #ISOLATION_REPEATABLE_READ}
  161. * and further prohibits the situation where one transaction reads all rows that
  162. * satisfy a {@code WHERE} condition, a second transaction inserts a row
  163. * that satisfies that {@code WHERE} condition, and the first transaction
  164. * re-reads for the same condition, retrieving the additional "phantom" row
  165. * in the second read.
  166. * @see java.sql.Connection#TRANSACTION_SERIALIZABLE
  167. */
  168. int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;
  169. /**
  170. * Use the default timeout of the underlying transaction system,
  171. * or none if timeouts are not supported.
  172. */
  173. int TIMEOUT_DEFAULT = -1;
  174. /**
  175. * Return the propagation behavior.
  176. * <p>Must return one of the {@code PROPAGATION_XXX} constants
  177. * defined on {@link TransactionDefinition this interface}.
  178. * @return the propagation behavior
  179. * @see #PROPAGATION_REQUIRED
  180. * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
  181. */
  182. int getPropagationBehavior();
  183. /**
  184. * Return the isolation level.
  185. * <p>Must return one of the {@code ISOLATION_XXX} constants
  186. * defined on {@link TransactionDefinition this interface}.
  187. * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}
  188. * or {@link #PROPAGATION_REQUIRES_NEW}.
  189. * <p>Note that a transaction manager that does not support custom isolation levels
  190. * will throw an exception when given any other level than {@link #ISOLATION_DEFAULT}.
  191. * @return the isolation level
  192. */
  193. int getIsolationLevel();
  194. /**
  195. * Return the transaction timeout.
  196. * <p>Must return a number of seconds, or {@link #TIMEOUT_DEFAULT}.
  197. * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}
  198. * or {@link #PROPAGATION_REQUIRES_NEW}.
  199. * <p>Note that a transaction manager that does not support timeouts will throw
  200. * an exception when given any other timeout than {@link #TIMEOUT_DEFAULT}.
  201. * @return the transaction timeout
  202. */
  203. int getTimeout();
  204. /**
  205. * Return whether to optimize as a read-only transaction.
  206. * <p>The read-only flag applies to any transaction context, whether
  207. * backed by an actual resource transaction
  208. * ({@link #PROPAGATION_REQUIRED}/{@link #PROPAGATION_REQUIRES_NEW}) or
  209. * operating non-transactionally at the resource level
  210. * ({@link #PROPAGATION_SUPPORTS}). In the latter case, the flag will
  211. * only apply to managed resources within the application, such as a
  212. * Hibernate {@code Session}.
  213. << * <p>This just serves as a hint for the actual transaction subsystem;
  214. * it will <i>not necessarily</i> cause failure of write access attempts.
  215. * A transaction manager which cannot interpret the read-only hint will
  216. * <i>not</i> throw an exception when asked for a read-only transaction.
  217. * @return {@code true} if the transaction is to be optimized as read-only
  218. * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean)
  219. * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
  220. */
  221. boolean isReadOnly();
  222. /**
  223. * Return the name of this transaction. Can be {@code null}.
  224. * <p>This will be used as the transaction name to be shown in a
  225. * transaction monitor, if applicable (for example, WebLogic's).
  226. * <p>In case of Spring's declarative transactions, the exposed name will be
  227. * the {@code fully-qualified class name + "." + method name} (by default).
  228. * @return the name of this transaction
  229. * @see org.springframework.transaction.interceptor.TransactionAspectSupport
  230. * @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName()
  231. */
  232. String getName();
  233. }

3、TransactionStatus事务状态信息

记录事务的状态信息,可以看看源码。理解一下大神的思想。


    
  1. /*
  2. * Copyright 2002-2013 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.transaction;
  17. import java.io.Flushable;
  18. /**
  19. * Representation of the status of a transaction.
  20. *
  21. * <p>Transactional code can use this to retrieve status information,
  22. * and to programmatically request a rollback (instead of throwing
  23. * an exception that causes an implicit rollback).
  24. *
  25. * <p>Derives from the SavepointManager interface to provide access
  26. * to savepoint management facilities. Note that savepoint management
  27. * is only available if supported by the underlying transaction manager.
  28. *
  29. * @author Juergen Hoeller
  30. * @since 27.03.2003
  31. * @see #setRollbackOnly()
  32. * @see PlatformTransactionManager#getTransaction
  33. * @see org.springframework.transaction.support.TransactionCallback#doInTransaction
  34. * @see org.springframework.transaction.interceptor.TransactionInterceptor#currentTransactionStatus()
  35. */
  36. public interface TransactionStatus extends SavepointManager, Flushable {
  37. /**
  38. * Return whether the present transaction is new (else participating
  39. * in an existing transaction, or potentially not running in an
  40. * actual transaction in the first place).
  41. */
  42. boolean isNewTransaction();
  43. /**
  44. * Return whether this transaction internally carries a savepoint,
  45. * that is, has been created as nested transaction based on a savepoint.
  46. * <p>This method is mainly here for diagnostic purposes, alongside
  47. * {@link #isNewTransaction()}. For programmatic handling of custom
  48. * savepoints, use SavepointManager's operations.
  49. * @see #isNewTransaction()
  50. * @see #createSavepoint
  51. * @see #rollbackToSavepoint(Object)
  52. * @see #releaseSavepoint(Object)
  53. */
  54. boolean hasSavepoint();
  55. /**
  56. * Set the transaction rollback-only. This instructs the transaction manager
  57. * that the only possible outcome of the transaction may be a rollback, as
  58. * alternative to throwing an exception which would in turn trigger a rollback.
  59. * <p>This is mainly intended for transactions managed by
  60. * {@link org.springframework.transaction.support.TransactionTemplate} or
  61. * {@link org.springframework.transaction.interceptor.TransactionInterceptor},
  62. * where the actual commit/rollback decision is made by the container.
  63. * @see org.springframework.transaction.support.TransactionCallback#doInTransaction
  64. * @see org.springframework.transaction.interceptor.TransactionAttribute#rollbackOn
  65. */
  66. void setRollbackOnly();
  67. /**
  68. * Return whether the transaction has been marked as rollback-only
  69. * (either by the application or by the transaction infrastructure).
  70. */
  71. boolean isRollbackOnly();
  72. /**
  73. * Flush the underlying session to the datastore, if applicable:
  74. * for example, all affected Hibernate/JPA sessions.
  75. */
  76. @Override
  77. void flush();
  78. /**
  79. * Return whether this transaction is completed, that is,
  80. * whether it has already been committed or rolled back.
  81. * @see PlatformTransactionManager#commit
  82. * @see PlatformTransactionManager#rollback
  83. */
  84. boolean isCompleted();
  85. }

4、事务的传播行为

一般来说我们都是一个业务层进行业务操作,如果涉及到一个业务层需要调用另一个业务层。这时就需要涉及到事务的传播行为用来规定在两个多个业务层中如何进行事务的管理。

(1)PROPAGATION_REQUIRED:支持当前事务,如果不存在,则新建一个(默认)。

(2)PROPAGATION_SUPPORTS:支持当前事务,如果不存在,则不使用事务。

(3)PROPAGATION_MANDATORY:支持当前事务,如果不存在,则抛出异常。

(4)PROPAGATION_REQUIRES_NEW:如果当前事务不存在,则新建一个事务。如果当前事务存在,挂起这个事务再新建一个事务。

(5)PROPAGATION_NOT_SUPPORTED:不支持当前事务,以不使用事务的方式运行,如果当前存在事务,则挂起事务。

(6)PROPAGATION_NEVER:以非事务的方式运行,如果存在事务,抛出异常。

(7)PROPAGATION_NESTED:如果当前事务存在,则嵌套事务来执行。

六、spring的事务三种实现方式

三种方式分别为编码式,xml配置方式,注解配置方式。编码式了解即可,实际开发都是后两种。

1、编码式

(1)在spring容器中配置核心事务管理器,依赖于连接池,连接池的配置方式可参考之前的文章。


    
  1. <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  2. <property name="dataSource" ref="dataSource" ></property>
  3. </bean>

(2)在spring容器中配置事务模板对象


    
  1. <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
  2. <property name="transactionManager" ref="transactionManager" ></property>
  3. </bean>

(3)在业务层中配置事务模板对象


    
  1. <bean name="accountDao" class="com.jichi.dao.AccountDaoImpl" >
  2. <property name="dataSource" ref="dataSource" ></property>
  3. </bean>
  4. <bean name="accountService" class="com.jichi.service.AccountServiceImpl" >
  5. <property name="ad" ref="accountDao" ></property>
  6. <property name="tt" ref="transactionTemplate" ></property>
  7. </bean>

(4)编写事务实现代码,在需要事务的方法中,用模板对象调用excute方法,实现其中的接口。重写接口中的方法,讲需要进行事务管理的代码放入其中。


    
  1. public class AccountServiceImpl implements AccountService {
  2. private AccountDao ad ;
  3. private TransactionTemplate tt;
  4. @Override
  5. public void transfer(final Integer from,final Integer to,final Double money) {
  6. tt.execute(new TransactionCallbackWithoutResult() {
  7. @Override
  8. protected void doInTransactionWithoutResult(TransactionStatus arg0) {
  9. //减钱
  10. ad.decreaseMoney(from, money);
  11. //加钱
  12. ad.increaseMoney(to, money);
  13. }
  14. });
  15. }
  16. }

2、xml方式

(1)导包

aopaliance,springaop,aspectJ,springaspectss

(2)配置事务管理器


    
  1. <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  2. <property name="dataSource" ref="dataSource" ></property>
  3. </bean>

(3)配置事务的通知,根据方法名进行匹配。


    
  1. <tx:advice id="txAdvice" transaction-manager="transactionManager" >
  2. <tx:attributes>
  3. <!-- 以方法为单位,指定方法应用什么事务属性
  4. isolation:隔离级别
  5. propagation:传播行为
  6. read-only:是否只读       timeout:过期时间        rollback-for        no-rollback-for
  7. -->
  8. <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  9. <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  10. <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  11. <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  12. <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  13. <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  14. <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
  15. <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
  16. <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
  17. </tx:attributes>
  18. </tx:advice>

(4)配置织入。首先配置切点。表示对哪些方法要进行增强。配置切面。pointcut-ref切点的名称,advice-ref通知的名称。


    
  1. <aop:config >
  2. <aop:pointcut expression="execution(* com.jichi.service.*ServiceImpl.*(..))" id="txPc"/>
  3. <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
  4. </aop:config>

3、注解方式

(1)配置事务管理器


    
  1. <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  2. <property name="dataSource" ref="dataSource" ></property>
  3. </bean>

(2)开启事务管理的注解

<tx:annotation-driven/>

   

(3)在使用事务的类上添加注解,在需要事务的方法上,打上注解,在注解中配置事务隔离级别,事务传播等信息。默认对该类中所有的方法,执行类上的配置,如果在某个方法上进行配置,则执行方法上的配置。


    
  1. @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
  2. public class AccountServiceImpl implements AccountService {
  3. private AccountDao ad ;
  4. private TransactionTemplate tt;
  5. @Override
  6. @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
  7. public void transfer(final Integer from,final Integer to,final Double money) {
  8. //减钱
  9. ad.decreaseMoney(from, money);
  10. int i = 1/0;
  11. //加钱
  12. ad.increaseMoney(to, money);
  13. }
  14. }

文章来源: blog.csdn.net,作者:经典鸡翅,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/hanqing456/article/details/111879008

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。