日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Hibernate悲观锁/乐观锁

發(fā)布時(shí)間:2025/4/16 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Hibernate悲观锁/乐观锁 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

如果需要保證數(shù)據(jù)訪問的排它性,則需對(duì)目標(biāo)數(shù)據(jù)加“鎖”,使其無法被其它程序修改

一,悲觀鎖

對(duì)數(shù)據(jù)被外界(包括本系統(tǒng)當(dāng)前的其它事務(wù)和來自外部系統(tǒng)的事務(wù)處理)修改持保守態(tài)度,通過數(shù)據(jù)庫提供的鎖機(jī)制實(shí)現(xiàn)

最常用的,是對(duì)查詢進(jìn)行加鎖(LockMode.UPGRADE和LockMode.UPGRADE_NOWAIT):

public class Test {public static void main(String[] args) {Configuration conf = new Configuration(); SessionFactory sessionFactory = conf.configure().buildSessionFactory(); Session sess = sessionFactory.openSession();Transaction tran = sess.beginTransaction();String hql = "from User where id = 1";Query query = sess.createQuery(hql);query.setLockOptions(LockOptions.UPGRADE);List<User> list = query.list();for(User user : list){System.out.print(user.getName()+" ");}System.out.println();tran.commit();sess.close(); } }

Hibernate會(huì)在生成的SQL后面加上for update子句:

Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from TEST_USER user0_ where user0_.id=1 for update longlong

通過for update子句,這條SQL鎖定了TEST_USER表中符合檢索條件的記錄,本次事務(wù)提交前,外界無法修改這些記錄,事務(wù)提交時(shí)會(huì)釋放事務(wù)過程中的鎖

Hibernate提供了2個(gè)鎖對(duì)象,LockMode和LockOptions:

通過LockOptions的源代碼,可以發(fā)現(xiàn)LockOptions只是LockMode的簡(jiǎn)單封裝(在LockMode的基礎(chǔ)上提供了timeout和scope):

...... /*** NONE represents LockMode.NONE (timeout + scope do not apply)*/ public static final LockOptions NONE = new LockOptions(LockMode.NONE);/*** READ represents LockMode.READ (timeout + scope do not apply)*/ public static final LockOptions READ = new LockOptions(LockMode.READ);/*** UPGRADE represents LockMode.UPGRADE (will wait forever for lock and* scope of false meaning only entity is locked)*/ public static final LockOptions UPGRADE = new LockOptions(LockMode.UPGRADE);public LockOptions(){}public LockOptions( LockMode lockMode) {this.lockMode = lockMode; } ..... public static final int NO_WAIT = 0;/*** Indicates that there is no timeout for the acquisition.* @see #getTimeOut*/ public static final int WAIT_FOREVER = -1;private int timeout = WAIT_FOREVER;private boolean scope=false; ......

LockOptions提供的加鎖機(jī)制要比LockMode少很多,但是LockMode多出的加鎖機(jī)制一般只是供Hibernate內(nèi)部實(shí)現(xiàn)使用的

保證了操作的獨(dú)占性,但嚴(yán)重影響數(shù)據(jù)庫性能


二,樂觀鎖

樂觀鎖大多基于數(shù)據(jù)版本記錄機(jī)制實(shí)現(xiàn),既為數(shù)據(jù)增加一個(gè)版本標(biāo)識(shí)

在數(shù)據(jù)庫中增加version列,用來記錄每行數(shù)據(jù)的版本

Hibernate配置文件中,version節(jié)點(diǎn)需要在id節(jié)點(diǎn)之后并緊跟id節(jié)點(diǎn)

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="com.po.User" table="TEST_USER"><id name="id" column="id" type="java.lang.Integer"><generator class="assigned"/></id><version name="version"column="version"type="java.lang.Integer"/><property name="name"column="name"type="java.lang.String"not-null="true"unique="true"length="20"/><property name="age"column="age"type="java.lang.Integer"not-null="true"unique="false"length="0"/></class> </hibernate-mapping>

每次更新User對(duì)象時(shí)時(shí),對(duì)應(yīng)行的version字段都在增加

public class Test {public static void main(String[] args) {Configuration conf = new Configuration(); SessionFactory sessionFactory = conf.configure().buildSessionFactory();Session sess1=sessionFactory.openSession();Session sess2=sessionFactory.openSession();try{User user1 = (User)sess1.get(User.class, 1);User user2 = (User)sess2.get(User.class, 1);System.out.println("v1="+user1.getVersion()+"--v2="+user2.getVersion());Transaction tx1 = sess1.beginTransaction();Transaction tx2 = sess2.beginTransaction();user1.setName("ll");tx1.commit();System.out.println("v1="+user1.getVersion()+"--v2="+user2.getVersion());user2.setName("LL");tx2.commit();}catch(Exception e){e.printStackTrace();}finally{sess1.close();sess2.close();}} }

運(yùn)行結(jié)果如下,可以看到由于tx1提交時(shí),version字段已經(jīng)被修改,tx2提交時(shí)會(huì)拋出異常:

Hibernate: select user0_.id as id0_0_, user0_.version as version0_0_, user0_.name as name0_0_, user0_.age as age0_0_ from TEST_USER user0_ where user0_.id=? Hibernate: select user0_.id as id0_0_, user0_.version as version0_0_, user0_.name as name0_0_, user0_.age as age0_0_ from TEST_USER user0_ where user0_.id=? v1=0--v2=0 Hibernate: update TEST_USER set version=?, name=?, age=? where id=? and version=? v1=1--v2=0 Hibernate: update TEST_USER set version=?, name=?, age=? where id=? and version=? Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.po.User#1]at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1932)at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2576)at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2476)at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2803)at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)at com.test.Test.main(Test.java:43)

除了使用version作為版本標(biāo)識(shí),還可以使用timestamp作為版本標(biāo)識(shí)

timestamp節(jié)點(diǎn)沒有type屬性:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="com.po.User" table="TEST_USER"><id name="id" column="id" type="java.lang.Integer"><generator class="assigned"/></id><timestamp name="updatetime"column="updatetime"/><property name="name"column="name"type="java.lang.String"not-null="true"unique="true"length="20"/><property name="age"column="age"type="java.lang.Integer"not-null="true"unique="false"length="0"/></class> </hibernate-mapping>

在某些情況下,不允許修改數(shù)據(jù)庫的表結(jié)構(gòu),此時(shí)Hibernate也有相應(yīng)的處理手段:

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="com.po.User" table="TEST_USER"optimistic-lock="all"dynamic-update="true"dynamic-insert="true"><id name="id" column="id" type="java.lang.Integer"><generator class="assigned"/></id><property name="name"column="name"type="java.lang.String"not-null="true"unique="true"length="20"/><property name="age"column="age"type="java.lang.Integer"not-null="true"unique="false"length="0"/></class> </hibernate-mapping>

此時(shí)Hibernate將使用User類的所有字段作為版本控制信息

樂觀鎖相較悲觀鎖提高了不少性能,但是有一定的局限性,由于是在應(yīng)用層加鎖,如果此時(shí)在數(shù)據(jù)中直接修改數(shù)據(jù)(或其它應(yīng)用程序修改數(shù)據(jù)庫中的數(shù)據(jù)),應(yīng)用層是無法感知到這種變化的,需要配合其它技術(shù)手段一起使用

?

轉(zhuǎn)載于:https://www.cnblogs.com/sean-zou/p/3709975.html

總結(jié)

以上是生活随笔為你收集整理的Hibernate悲观锁/乐观锁的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。