大家對以下3個措施定然不面生,一些IDE生成的代碼等閑都有下面三個措施:
public Person merge(Person detachedInstance) { log.debug("merging Person instance"); try { Person result = (Person) getSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Person instance) { log.debug("attaching dirty Person instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Person instance) { log.debug("attaching clean Person instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } }
merge:將傳入的detached事態(tài)的對象的屬性復制到永遠化對象中,并歸來該永遠化對象 。萬一該session中未曾關(guān)系的永遠化對象,加載一個,萬一傳入對象未保留,保留一個副本并作為永遠對象歸來,傳入對象依舊堅持detached事態(tài)。
attachDirty:將傳入的對象永遠化并保留。萬一對象未保留(Transient事態(tài)),調(diào)用save措施保留。萬一對象已保留(Detached事態(tài)),調(diào)用update措施將對象與Session重新關(guān)系。
attachClean:將傳入的對象事態(tài)設(shè)置為Transient事態(tài)。
解釋一下,在Hibernate中的對象有三種事態(tài),即:
俄而事態(tài)(Transient)、永遠事態(tài)(Persistent)、脫管事態(tài)(Detached)
1、俄而事態(tài)(Transient)
由new號召開發(fā)內(nèi)存空間的Java對象,也即便平時所純熟的等閑Java對象。
如:Person p = new Person();
俄而對象個性:
(1)不和Session實例關(guān)系
(2)在數(shù)據(jù)庫中未曾和俄而對象關(guān)系的登記
2、永遠事態(tài)(Persistent)
永遠的實例在數(shù)據(jù)庫中有對應(yīng)的登記,并具有一個永遠化標識(identifier).
永遠對象總是與Session和Transaction相干聯(lián),在一個Session中,對永遠對象的改換不會即刻對數(shù)據(jù)庫舉行改變,而定然在Transaction終止,也即便厲行commit()爾后,才在數(shù)據(jù)庫中懇摯運行SQL舉行改變,永遠對象的事態(tài)才會與數(shù)據(jù)庫舉行同步。在同步之前的永遠對象稱為臟(dirty)對象。
俄而對象轉(zhuǎn)為永遠對象:
(1) 穿越Session的save()和saveOrUpdate()措施把一個俄而對象與數(shù)據(jù)庫相干聯(lián),這個俄而對象就成為永遠化對象。
(2) 利用fine(),無線通訊模塊get(),load()和iterater()待措施查詢到的數(shù)據(jù)對象,將成為永遠化對象。
永遠化對象的個性:
(1) 和Session實例關(guān)系
(2) 在數(shù)據(jù)庫中有和永遠對象關(guān)系的登記
3、脫管事態(tài)(Detached)
與永遠對象關(guān)系的Session被關(guān)閉后,對象就變?yōu)槊摴軐ο?。對脫管對象的引用依舊管用,對象可繼續(xù)被修正。
脫管對象個性:
(1) 性質(zhì)上和俄而對象雷同
(2) 只是比愛俄而對象多了一個數(shù)據(jù)庫登記標識值id.
永遠對象轉(zhuǎn)為脫管對象:
當厲行close()或clear(),evict()爾后,永遠對象會變?yōu)槊摴軐ο蟆?
俄而對象轉(zhuǎn)為永遠對象:
穿越Session的update(),saveOrUpdate()和lock()等措施,把脫管對象變?yōu)橛肋h對象。