Spring中 @Transactional 注解的限制
1. 同一個類中, 一個nan-transactional的方法去調用transactional的方法, 事務會失效
If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transational) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.
2. 在private方法上標注transactional, 事務無效
When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.
測試代碼
TestCase01.java
package com.rockbb.test.api.service; public interface TestCase01 { void init(); void clean(); void txnInLocalPrivate(); void txnInLocalPublic(); void txnInOpenPublic(); void txnInOpenPublicByInvokePrivate(); void txnInOpenPublicByInvokePublic(); }
TestCase01Impl.java
package com.rockbb.test.impl.service.impl; import com.rockbb.test.api.dto.AccountDTO; import com.rockbb.test.api.dto.AccountDetailDTO; import com.rockbb.test.api.service.TestCase01; import com.rockbb.test.impl.mapper.AccountDetailMapper; import com.rockbb.test.impl.mapper.AccountMapper; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; @Repository("testCase01") public class TestCase01Impl implements TestCase01 { @Resource(name="accountMapper") private AccountMapper accountMapper; @Resource(name="accountDetailMapper") private AccountDetailMapper accountDetailMapper; @Resource(name="testCase01") private TestCase01 testCase01; /** * 無效, 未回退 * * 結論: 在私有方法上加事務注解無效 */ @Override public void txnInLocalPrivate() { localPrivate(); } /** * 無效, 未回退 * * 結論: 在公有方法上事務注解, 再通過接口方法調用, 無效 */ @Override public void txnInLocalPublic() { localPublic(); } /** * 有效, 無論下面調用的是否是私有方法 * * 結論: 在接口方法上加事務, 無論下面調用的是否是私有方法, 都有效 */ @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void txnInOpenPublic() { localPrivate(); } @Override public void txnInOpenPublicByInvokePrivate() { } /** * * 結論: 普通接口方法直接調用同類帶事務的方法, 無效. 通過接口調用則有效 */ @Override public void txnInOpenPublicByInvokePublic() { //txnInOpenPublic(); // 無效 testCase01.txnInOpenPublic(); // 有效 } @Override public void init() { accountMapper.truncate(); for (int i = 0; i < 10; i++) { BigDecimal amount = BigDecimal.valueOf(i * 10); add(String.valueOf(i), BigDecimal.ZERO); increase(String.valueOf(i), BigDecimal.valueOf(100 + i)); } } @Override public void clean() { accountMapper.truncate(); } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) private void localPrivate() { AccountDTO dto = new AccountDTO().initialize(); dto.setId("test"); dto.setAmount(BigDecimal.ZERO); accountMapper.insert(dto); throw new RuntimeException("localPrivate"); } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void localPublic() { AccountDTO dto = new AccountDTO().initialize(); dto.setId("test"); dto.setAmount(BigDecimal.ZERO); accountMapper.insert(dto); throw new RuntimeException("localPublic"); } public void openPublic() { AccountDTO dto = new AccountDTO().initialize(); dto.setId("test"); dto.setAmount(BigDecimal.ZERO); accountMapper.insert(dto); throw new RuntimeException("openPublic"); } private int add(String id, BigDecimal amount) { AccountDTO dto = new AccountDTO().initialize(); dto.setId(id); dto.setAmount(amount); return accountMapper.insert(dto); } private int increase(String id, BigDecimal amount) { AccountDTO dto = accountMapper.select(id); AccountDetailDTO detail = new AccountDetailDTO().initialize(); detail.setAmount(amount); detail.setPreAmount(dto.getAmount()); dto.setAmount(dto.getAmount().add(amount)); detail.setPostAmount(dto.getAmount()); if (accountMapper.update(dto) != 1) { throw new RuntimeException(); } return accountDetailMapper.insert(detail); } }
TestCase02.java
package com.rockbb.test.api.service; public interface TestCase02 { void txnInOpenPublicByPublic(); void txnInOpenPublicByPrivate(); }
TestCase02Impl.java
package com.rockbb.test.impl.service.impl; import com.rockbb.test.api.service.TestCase01; import com.rockbb.test.api.service.TestCase02; import org.springframework.stereotype.Repository; import javax.annotation.Resource; @Repository("testCase02") public class TestCase02Impl implements TestCase02 { @Resource(name="testCase01") private TestCase01 testCase01; /** * 有效 * * 結論: 在接口方法上加事務, 再被他類的接口方法調用, 無論此接口方法是否加事務, 都有效 */ @Override public void txnInOpenPublicByPublic() { testCase01.txnInOpenPublic(); } /** * 有效 * * 結論: 在接口方法上加事務, 再被他類的私有方法調用后, 依然有效 */ @Override public void txnInOpenPublicByPrivate() { localPrivate(); } private void localPrivate() { testCase01.txnInOpenPublic(); } }
測試樣例 AccountCheckTest.java
package com.rockbb.test.test; import com.rockbb.test.api.service.TestCase01; import com.rockbb.test.api.service.TestCase02; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/spring/spring-commons.xml"}) public class AccountCheckTest { private static final Logger logger = LoggerFactory.getLogger(AccountCheckTest.class); @Resource(name="testCase01") private TestCase01 testCase01; @Resource(name="testCase02") private TestCase02 testCase02; @Test public void test01() { testCase01.init(); try { testCase01.txnInLocalPrivate(); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Test public void test02() { testCase01.init(); try { testCase01.txnInLocalPublic(); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Test public void test03() { testCase01.init(); try { testCase01.txnInOpenPublic(); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Test public void test04() { testCase01.init(); try { testCase02.txnInOpenPublicByPublic(); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Test public void test05() { testCase01.init(); try { testCase02.txnInOpenPublicByPrivate(); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Test public void test06() { testCase01.init(); try { testCase01.txnInOpenPublicByInvokePublic(); } catch (Exception e) { logger.error(e.getMessage(), e); } } }
結論
- @Transactional 加於private方法, 無效
- @Transactional 加於未加入接口的public方法, 再通過普通接口方法調用, 無效
- @Transactional 加於接口方法, 無論下面調用的是private或public方法, 都有效
- @Transactional 加於接口方法后, 被本類普通接口方法直接調用, 無效
- @Transactional 加於接口方法后, 被本類普通接口方法通過接口調用, 有效
- @Transactional 加於接口方法后, 被它類的接口方法調用, 有效
- @Transactional 加於接口方法后, 被它類的私有方法調用后, 有效
- 總結: Transactional是否生效, 僅取決於是否加載於接口方法, 並且是否通過接口方法調用(而不是本類調用)
@Transactional(readOnly = true) 的含義
執行單條查詢語句時, 數據庫默認支持SQL執行期間的讀一致性. 而執行多條查詢語句(例如統計查詢, 報表查詢)時, 多條查詢SQL必須保證整體的讀一致性, 否則在每條查詢之間數據可能發生變動, 導致最終的查詢結果出現數據不一致的錯誤,此時應該啟用事務支持.
read-only="true"表示該事務為只讀事務, 上面的多條查詢可以使用只讀事務. 由於只讀事務不存在對數據的修改, 因此數據庫將會為只讀事務提供一些優化手段, 例如Oracle對於只讀事務不啟動回滾段, 不記錄回滾log.
在JDBC中指定只讀事務的辦法為 connection.setReadOnly(true), Hibernate中指定只讀事務的辦法為 session.setFlushMode(FlushMode.NEVER). 在Spring的Hibernate封裝中,指定只讀事務的辦法為bean配置文件中 prop屬性增加“read-Only”. 或者用注解方式@Transactional(readOnly=true)
在將事務設置成只讀后, 相當於將數據庫設置成只讀數據庫, 此時若要進行寫的操作會報錯.