相信每一個人都被問過無數次Spring聲明式事務的隔離級別和傳播機制吧!今天我也來講說這兩個東西.java
加入一個小插曲,
一天電話裏有人問我聲明式事務隔離級別有哪幾種,
我就回答了7種,
他問我Spring的版本,
我回答爲3.0。
他說那應該是2.5的,3.0好像變少了。
我回答這個沒有確認過。
後來我就google了一下,沒發現什麼痕跡說明事務的隔離級別變少了,也查了下官方文檔,也沒有相關的說明。索性在github上clone一下Spring的源碼,看看源碼中有幾種就是幾種了唄。
後來想一想那天他那麼問我徹底多是一個坑啊,由於交談的過程當中挖過至少兩個坑了。再者說,Spring要向下兼容的,若是少了怎麼處理呢?固然這兩點都是我本身的猜想。
在Spring中,聲明式事務是用事務參數來定義的。一個事務參數就是對事務策略應該如何應用到某個方法的一段描述,以下圖所示一個事務參數共有5個方面組成:git
事務的第一個方面是傳播行爲。傳播行爲定義關於客戶端和被調用方法的事務邊界。Spring定義了7中傳播行爲。 github
傳播行爲 | 意義 |
---|---|
PROPAGATION_MANDATORY | 表示該方法必須運行在一個事務中。若是當前沒有事務正在發生,將拋出一個異常 |
PROPAGATION_NESTED | 表示若是當前正有一個事務在進行中,則該方法應當運行在一個嵌套式事務中。被嵌套的事務能夠獨立於封裝事務進行提交或回滾。若是封裝事務不存在,行爲就像PROPAGATION_REQUIRES同樣。 |
PROPAGATION_NEVER | 表示當前的方法不該該在一個事務中運行。若是一個事務正在進行,則會拋出一個異常。 |
PROPAGATION_NOT_SUPPORTED | 表示該方法不該該在一個事務中運行。若是一個現有事務正在進行中,它將在該方法的運行期間被掛起。 |
PROPAGATION_SUPPORTS | 表示當前方法不須要事務性上下文,可是若是有一個事務已經在運行的話,它也能夠在這個事務裏運行。 |
PROPAGATION_REQUIRES_NEW | 表示當前方法必須在它本身的事務裏運行。一個新的事務將被啓動,並且若是有一個現有事務在運行的話,則將在這個方法運行期間被掛起。 |
PROPAGATION_REQUIRES | 表示當前方法必須在一個事務中運行。若是一個現有事務正在進行中,該方法將在那個事務中運行,不然就要開始一個新事務。 |
傳播規則回答了這樣一個問題,就是一個新的事務應該被啓動仍是被掛起,或者是一個方法是否應該在事務性上下文中運行。spring
聲明式事務的第二個方面是隔離級別。隔離級別定義一個事務可能受其餘併發事務活動活動影響的程度。另外一種考慮一個事務的隔離級別的方式,是把它想象爲那個事務對於事物處理數據的自私程度。sql
在一個典型的應用程序中,多個事務同時運行,常常會爲了完成他們的工做而操做同一個數據。併發雖然是必需的,可是會致使一下問題:數據庫
在理想狀態下,事務之間將徹底隔離,從而能夠防止這些問題發生。然而,徹底隔離會影響性能,由於隔離常常牽扯到鎖定在數據庫中的記錄(並且有時是鎖定完整的數據表)。侵佔性的鎖定會阻礙併發,要求事務相互等待來完成工做。express
考慮到徹底隔離會影響性能,並且並非全部應用程序都要求徹底隔離,因此有時能夠在事務隔離方面靈活處理。所以,就會有好幾個隔離級別。apache
隔離級別 | 含義 |
---|---|
ISOLATION_DEFAULT | 使用後端數據庫默認的隔離級別。 |
ISOLATION_READ_UNCOMMITTED | 容許讀取還沒有提交的更改。可能致使髒讀、幻影讀或不可重複讀。 |
ISOLATION_READ_COMMITTED | 容許從已經提交的併發事務讀取。可防止髒讀,但幻影讀和不可重複讀仍可能會發生。 |
ISOLATION_REPEATABLE_READ | 對相同字段的屢次讀取的結果是一致的,除非數據被當前事務自己改變。可防止髒讀和不可重複讀,但幻影讀仍可能發生。 |
ISOLATION_SERIALIZABLE | 徹底服從ACID的隔離級別,確保不發生髒讀、不可重複讀和幻影讀。這在全部隔離級別中也是最慢的,由於它一般是經過徹底鎖定當前事務所涉及的數據表來完成的。 |
聲明式事務的第三個特性是它是不是一個只讀事務。若是一個事務只對後端數據庫執行讀操做,那麼該數據庫就可能利用那個事務的只讀特性,採起某些優化 措施。經過把一個事務聲明爲只讀,能夠給後端數據庫一個機會來應用那些它認爲合適的優化措施。因爲只讀的優化措施是在一個事務啓動時由後端數據庫實施的, 所以,只有對於那些具備可能啓動一個新事務的傳播行爲(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、 ROPAGATION_NESTED)的方法來講,將事務聲明爲只讀纔有意義。後端
此外,若是使用Hibernate做爲持久化機制,那麼把一個事務聲明爲只讀,將使Hibernate的flush模式被設置爲FLUSH_NEVER。這就告訴Hibernate避免和數據庫進行沒必要要的對象同步,從而把全部更新延遲到事務的結束。併發
爲了使一個應用程序很好地執行,它的事務不能運行太長時間。所以,聲明式事務的下一個特性就是它的超時。
假設事務的運行時間變得格外的長,因爲事務可能涉及對後端數據庫的鎖定,因此長時間運行的事務會沒必要要地佔用數據庫資源。這時就能夠聲明一個事務在特定秒數後自動回滾,沒必要等它本身結束。
因爲超時時鐘在一個事務啓動的時候開始的,所以,只有對於那些具備可能啓動一個新事務的傳播行爲(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、ROPAGATION_NESTED)的方法來講,聲明事務超時纔有意義。
事務五邊形的對後一個邊是一組規則,它們定義哪些異常引發回滾,哪些不引發。在默認設置下,事務只在出現運行時異常(runtime exception)時回滾,而在出現受檢查異常(checked exception)時不回滾(這一行爲和EJB中的回滾行爲是一致的)。
不過,也能夠聲明在出現特定受檢查異常時像運行時異常同樣回滾。一樣,也能夠聲明一個事務在出現特定的異常時不回滾,即便那些異常是運行時一場。
標題是隻有事務的隔離級別和傳播機制,卻順帶這把聲明式事務的五個特性都講述了一遍。:)
文章開頭說過查看Spring中事務的源碼來確認3.0版本及以後事務的傳播機制是否減小了,其實在TransactionDefinition這個接口中定義了事務的隔離級別、傳播機制、只讀以及超時相關的所有信息。源碼以下,感興趣的能夠本身對照一下,看看英文註釋。
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction; import java.sql.Connection; /** * Interface that defines Spring-compliant transaction properties. * Based on the propagation behavior definitions analogous to EJB CMT attributes. * * <p>Note that isolation level and timeout settings will not get applied unless * an actual new transaction gets started. As only {@link #PROPAGATION_REQUIRED}, * {@link #PROPAGATION_REQUIRES_NEW} and {@link #PROPAGATION_NESTED} can cause * that, it usually doesn't make sense to specify those settings in other cases. * Furthermore, be aware that not all transaction managers will support those * advanced features and thus might throw corresponding exceptions when given * non-default values. * * <p>The {@link #isReadOnly() read-only flag} applies to any transaction context, * whether backed by an actual resource transaction or operating non-transactionally * at the resource level. In the latter case, the flag will only apply to managed * resources within the application, such as a Hibernate <code>Session</code>. * * @author Juergen Hoeller * @since 08.05.2003 * @see PlatformTransactionManager#getTransaction(TransactionDefinition) * @see org.springframework.transaction.support.DefaultTransactionDefinition * @see org.springframework.transaction.interceptor.TransactionAttribute */ public interface TransactionDefinition { /** * Support a current transaction; create a new one if none exists. * Analogous to the EJB transaction attribute of the same name. * <p>This is typically the default setting of a transaction definition, * and typically defines a transaction synchronization scope. */ int PROPAGATION_REQUIRED = 0; /** * Support a current transaction; execute non-transactionally if none exists. * Analogous to the EJB transaction attribute of the same name. * <p><b>NOTE:</b> For transaction managers with transaction synchronization, * <code>PROPAGATION_SUPPORTS</code> is slightly different from no transaction * at all, as it defines a transaction scope that synchronization might apply to. * As a consequence, the same resources (a JDBC <code>Connection</code>, a * Hibernate <code>Session</code>, etc) will be shared for the entire specified * scope. Note that the exact behavior depends on the actual synchronization * configuration of the transaction manager! * <p>In general, use <code>PROPAGATION_SUPPORTS</code> with care! In particular, do * not rely on <code>PROPAGATION_REQUIRED</code> or <code>PROPAGATION_REQUIRES_NEW</code> * <i>within</i> a <code>PROPAGATION_SUPPORTS</code> scope (which may lead to * synchronization conflicts at runtime). If such nesting is unavoidable, make sure * to configure your transaction manager appropriately (typically switching to * "synchronization on actual transaction"). * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION */ int PROPAGATION_SUPPORTS = 1; /** * Support a current transaction; throw an exception if no current transaction * exists. Analogous to the EJB transaction attribute of the same name. * <p>Note that transaction synchronization within a <code>PROPAGATION_MANDATORY</code> * scope will always be driven by the surrounding transaction. */ int PROPAGATION_MANDATORY = 2; /** * Create a new transaction, suspending the current transaction if one exists. * Analogous to the EJB transaction attribute of the same name. * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box * on all transaction managers. This in particular applies to * {@link org.springframework.transaction.jta.JtaTransactionManager}, * which requires the <code>javax.transaction.TransactionManager</code> * to be made available it to it (which is server-specific in standard J2EE). * <p>A <code>PROPAGATION_REQUIRES_NEW</code> scope always defines its own * transaction synchronizations. Existing synchronizations will be suspended * and resumed appropriately. * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager */ int PROPAGATION_REQUIRES_NEW = 3; /** * Do not support a current transaction; rather always execute non-transactionally. * Analogous to the EJB transaction attribute of the same name. * <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box * on all transaction managers. This in particular applies to * {@link org.springframework.transaction.jta.JtaTransactionManager}, * which requires the <code>javax.transaction.TransactionManager</code> * to be made available it to it (which is server-specific in standard J2EE). * <p>Note that transaction synchronization is <i>not</i> available within a * <code>PROPAGATION_NOT_SUPPORTED</code> scope. Existing synchronizations * will be suspended and resumed appropriately. * @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager */ int PROPAGATION_NOT_SUPPORTED = 4; /** * Do not support a current transaction; throw an exception if a current transaction * exists. Analogous to the EJB transaction attribute of the same name. * <p>Note that transaction synchronization is <i>not</i> available within a * <code>PROPAGATION_NEVER</code> scope. */ int PROPAGATION_NEVER = 5; /** * Execute within a nested transaction if a current transaction exists, * behave like {@link #PROPAGATION_REQUIRED} else. There is no analogous * feature in EJB. * <p><b>NOTE:</b> Actual creation of a nested transaction will only work on * specific transaction managers. Out of the box, this only applies to the JDBC * {@link org.springframework.jdbc.datasource.DataSourceTransactionManager} * when working on a JDBC 3.0 driver. Some JTA providers might support * nested transactions as well. * @see org.springframework.jdbc.datasource.DataSourceTransactionManager */ int PROPAGATION_NESTED = 6; /** * Use the default isolation level of the underlying datastore. * All other levels correspond to the JDBC isolation levels. * @see java.sql.Connection */ int ISOLATION_DEFAULT = -1; /** * Indicates that dirty reads, non-repeatable reads and phantom reads * can occur. * <p>This level allows a row changed by one transaction to be read by another * transaction before any changes in that row have been committed (a "dirty read"). * If any of the changes are rolled back, the second transaction will have * retrieved an invalid row. * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED */ int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED; /** * Indicates that dirty reads are prevented; non-repeatable reads and * phantom reads can occur. * <p>This level only prohibits a transaction from reading a row * with uncommitted changes in it. * @see java.sql.Connection#TRANSACTION_READ_COMMITTED */ int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED; /** * Indicates that dirty reads and non-repeatable reads are prevented; * phantom reads can occur. * <p>This level prohibits a transaction from reading a row with uncommitted changes * in it, and it also prohibits the situation where one transaction reads a row, * a second transaction alters the row, and the first transaction re-reads the row, * getting different values the second time (a "non-repeatable read"). * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ */ int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ; /** * Indicates that dirty reads, non-repeatable reads and phantom reads * are prevented. * <p>This level includes the prohibitions in {@link #ISOLATION_REPEATABLE_READ} * and further prohibits the situation where one transaction reads all rows that * satisfy a <code>WHERE</code> condition, a second transaction inserts a row * that satisfies that <code>WHERE</code> condition, and the first transaction * re-reads for the same condition, retrieving the additional "phantom" row * in the second read. * @see java.sql.Connection#TRANSACTION_SERIALIZABLE */ int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE; /** * Use the default timeout of the underlying transaction system, * or none if timeouts are not supported. */ int TIMEOUT_DEFAULT = -1; /** * Return the propagation behavior. * <p>Must return one of the <code>PROPAGATION_XXX</code> constants * defined on {@link TransactionDefinition this interface}. * @return the propagation behavior * @see #PROPAGATION_REQUIRED * @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive() */ int getPropagationBehavior(); /** * Return the isolation level. * <p>Must return one of the <code>ISOLATION_XXX</code> constants * defined on {@link TransactionDefinition this interface}. * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED} * or {@link #PROPAGATION_REQUIRES_NEW}. * <p>Note that a transaction manager that does not support custom isolation levels * will throw an exception when given any other level than {@link #ISOLATION_DEFAULT}. * @return the isolation level */ int getIsolationLevel(); /** * Return the transaction timeout. * <p>Must return a number of seconds, or {@link #TIMEOUT_DEFAULT}. * <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED} * or {@link #PROPAGATION_REQUIRES_NEW}. * <p>Note that a transaction manager that does not support timeouts will throw * an exception when given any other timeout than {@link #TIMEOUT_DEFAULT}. * @return the transaction timeout */ int getTimeout(); /** * Return whether to optimize as a read-only transaction. * <p>The read-only flag applies to any transaction context, whether * backed by an actual resource transaction * ({@link #PROPAGATION_REQUIRED}/{@link #PROPAGATION_REQUIRES_NEW}) or * operating non-transactionally at the resource level * ({@link #PROPAGATION_SUPPORTS}). In the latter case, the flag will * only apply to managed resources within the application, such as a * Hibernate <code>Session</code>. * <p>This just serves as a hint for the actual transaction subsystem; * it will <i>not necessarily</i> cause failure of write access attempts. * A transaction manager which cannot interpret the read-only hint will * <i>not</i> throw an exception when asked for a read-only transaction. * @return <code>true</code> if the transaction is to be optimized as read-only * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean) * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly() */ boolean isReadOnly(); /** * Return the name of this transaction. Can be <code>null</code>. * <p>This will be used as the transaction name to be shown in a * transaction monitor, if applicable (for example, WebLogic's). * <p>In case of Spring's declarative transactions, the exposed name will be * the <code>fully-qualified class name + "." + method name</code> (by default). * @return the name of this transaction * @see org.springframework.transaction.interceptor.TransactionAspectSupport * @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName() */ String getName(); }
仍是以爲不安心,發兩張圖證實隔離級別和傳播機制: