hibernate工厂模式_Hibernate锁定模式–乐观锁定模式如何工作
hibernate工廠模式
顯式樂觀鎖定
在上一篇文章中 ,我介紹了Java持久性鎖定的基本概念。
隱式鎖定機制可防止丟失更新 ,它適用于我們可以主動修改的實體。 盡管隱式樂觀鎖定是一種廣泛使用的技術,但很少有人了解顯式樂觀鎖定模式的內(nèi)部工作原理。
當鎖定的實體始終由某些外部機制修改時,顯式樂觀鎖定可以防止數(shù)據(jù)完整性異常。
產(chǎn)品訂購用例
假設我們有以下域模型:
我們的用戶愛麗絲想訂購產(chǎn)品。 購買過程如下:
- 愛麗絲加載產(chǎn)品實體
- 因為價格方便,她決定訂購產(chǎn)品
- 價格引擎批處理作業(yè)更改了產(chǎn)品價格(考慮了貨幣更改,稅項更改和市場營銷活動)
- 愛麗絲發(fā)出訂單而沒有注意到價格變動
隱式鎖定的缺點
首先,我們將測試隱式鎖定機制是否可以防止此類異常。 我們的測試用例如下所示:
doInTransaction(new TransactionCallable<Void>() {@Overridepublic Void execute(Session session) {final Product product = (Product) session.get(Product.class, 1L);try {executeAndWait(new Callable<Void>() {@Overridepublic Void call() throws Exception {return doInTransaction(new TransactionCallable<Void>() {@Overridepublic Void execute(Session _session) {Product _product = (Product) _session.get(Product.class, 1L);assertNotSame(product, _product);_product.setPrice(BigDecimal.valueOf(14.49));return null;}});}});} catch (Exception e) {fail(e.getMessage());}OrderLine orderLine = new OrderLine(product);session.persist(orderLine);return null;} });測試生成以下輸出:
#Alice selects a Product Query:{[select abstractlo0_.id as id1_1_0_, abstractlo0_.description as descript2_1_0_, abstractlo0_.price as price3_1_0_, abstractlo0_.version as version4_1_0_ from product abstractlo0_ where abstractlo0_.id=?][1]} #The price engine selects the Product as well Query:{[select abstractlo0_.id as id1_1_0_, abstractlo0_.description as descript2_1_0_, abstractlo0_.price as price3_1_0_, abstractlo0_.version as version4_1_0_ from product abstractlo0_ where abstractlo0_.id=?][1]} #The price engine changes the Product price Query:{[update product set description=?, price=?, version=? where id=? and version=?][USB Flash Drive,14.49,1,1,0]} #The price engine transaction is committed DEBUG [pool-2-thread-1]: o.h.e.t.i.j.JdbcTransaction - committed JDBC Connection#Alice inserts an OrderLine without realizing the Product price change Query:{[insert into order_line (id, product_id, unitPrice, version) values (default, ?, ?, ?)][1,12.99,0]} #Alice transaction is committed unaware of the Product state change DEBUG [main]: o.h.e.t.i.j.JdbcTransaction - committed JDBC Connection隱式的樂觀鎖定機制無法檢測到外部更改,除非實體也被當前的持久性上下文更改。 為了防止發(fā)出過時的Product狀態(tài)訂單,我們需要在Product實體上應用顯式鎖。
明確鎖定救援
Java Persistence LockModeType.OPTIMISTIC是此類情況的合適候選者,因此我們將對其進行測試。
Hibernate帶有LockModeConverter實用程序,該實用程序能夠?qū)⑷魏蜫ava Persistence LockModeType映射到與其關聯(lián)的Hibernate LockMode 。
為簡單起見,我們將使用特定于Hibernate的LockMode.OPTIMISTIC ,該方法實際上與其Java持久性對應項相同。
根據(jù)Hibernate文檔,顯式的OPTIMISTIC鎖定模式將:
假設交易不會對實體產(chǎn)生競爭。 實體版本將在交易結(jié)束時進行驗證。
我將調(diào)整測試用例,改為使用顯式OPTIMISTIC鎖定:
try {doInTransaction(new TransactionCallable<Void>() {@Overridepublic Void execute(Session session) {final Product product = (Product) session.get(Product.class, 1L, new LockOptions(LockMode.OPTIMISTIC));executeAndWait(new Callable<Void>() {@Overridepublic Void call() throws Exception {return doInTransaction(new TransactionCallable<Void>() {@Overridepublic Void execute(Session _session) {Product _product = (Product) _session.get(Product.class, 1L);assertNotSame(product, _product);_product.setPrice(BigDecimal.valueOf(14.49));return null;}});}});OrderLine orderLine = new OrderLine(product);session.persist(orderLine);return null;}});fail("It should have thrown OptimisticEntityLockException!"); } catch (OptimisticEntityLockException expected) {LOGGER.info("Failure: ", expected); }新的測試版本生成以下輸出:
#Alice selects a Product Query:{[select abstractlo0_.id as id1_1_0_, abstractlo0_.description as descript2_1_0_, abstractlo0_.price as price3_1_0_, abstractlo0_.version as version4_1_0_ from product abstractlo0_ where abstractlo0_.id=?][1]} #The price engine selects the Product as well Query:{[select abstractlo0_.id as id1_1_0_, abstractlo0_.description as descript2_1_0_, abstractlo0_.price as price3_1_0_, abstractlo0_.version as version4_1_0_ from product abstractlo0_ where abstractlo0_.id=?][1]} #The price engine changes the Product price Query:{[update product set description=?, price=?, version=? where id=? and version=?][USB Flash Drive,14.49,1,1,0]} #The price engine transaction is committed DEBUG [pool-1-thread-1]: o.h.e.t.i.j.JdbcTransaction - committed JDBC Connection#Alice inserts an OrderLine Query:{[insert into order_line (id, product_id, unitPrice, version) values (default, ?, ?, ?)][1,12.99,0]} #Alice transaction verifies the Product version Query:{[select version from product where id =?][1]} #Alice transaction is rolled back due to Product version mismatch INFO [main]: c.v.h.m.l.c.LockModeOptimisticTest - Failure: org.hibernate.OptimisticLockException: Newer version [1] of entity [[com.vladmihalcea.hibernate.masterclass.laboratory.concurrency. AbstractLockModeOptimisticTest$Product#1]] found in database操作流程如下:
在交易結(jié)束時檢查產(chǎn)品版本。 任何版本不匹配都會觸發(fā)異常和事務回滾。
比賽條件風險
不幸的是,應用程序級別的版本檢查和事務提交不是原子操作。 該檢查發(fā)生在EntityVerifyVersionProcess中 ,在交易之前提交階段:
public class EntityVerifyVersionProcess implements BeforeTransactionCompletionProcess {private final Object object;private final EntityEntry entry;/*** Constructs an EntityVerifyVersionProcess** @param object The entity instance* @param entry The entity's referenced EntityEntry*/public EntityVerifyVersionProcess(Object object, EntityEntry entry) {this.object = object;this.entry = entry;}@Overridepublic void doBeforeTransactionCompletion(SessionImplementor session) {final EntityPersister persister = entry.getPersister();final Object latestVersion = persister.getCurrentVersion( entry.getId(), session );if ( !entry.getVersion().equals( latestVersion ) ) {throw new OptimisticLockException(object,"Newer version [" + latestVersion +"] of entity [" + MessageHelper.infoString( entry.getEntityName(), entry.getId() ) +"] found in database");}} }調(diào)用AbstractTransactionImpl.commit()方法,將執(zhí)行before-transaction-commit階段,然后提交實際事務:
@Override public void commit() throws HibernateException {if ( localStatus != LocalStatus.ACTIVE ) {throw new TransactionException( "Transaction not successfully started" );}LOG.debug( "committing" );beforeTransactionCommit();try {doCommit();localStatus = LocalStatus.COMMITTED;afterTransactionCompletion( Status.STATUS_COMMITTED );}catch (Exception e) {localStatus = LocalStatus.FAILED_COMMIT;afterTransactionCompletion( Status.STATUS_UNKNOWN );throw new TransactionException( "commit failed", e );}finally {invalidate();afterAfterCompletion();} }在支票和實際交易提交之間,其他交易在很短的時間內(nèi)默默地提交產(chǎn)品價格變化。
結(jié)論
顯式的OPTIMISTIC鎖定策略為過時的狀態(tài)異常提供了有限的保護。 此競爭條件是“檢查時間”到“使用時間數(shù)據(jù)完整性異常”的典型情況。
在下一篇文章中,我將解釋如何使用explicit lock upgrade技術保存該示例。
- 代碼可在GitHub上獲得 。
翻譯自: https://www.javacodegeeks.com/2015/01/hibernate-locking-patterns-how-does-optimistic-lock-mode-work.html
hibernate工廠模式
總結(jié)
以上是生活随笔為你收集整理的hibernate工厂模式_Hibernate锁定模式–乐观锁定模式如何工作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linuxzip解压命令(linux z
- 下一篇: linux新建文件的命令有哪些(linu