今天我在hibernate 進(jìn)行 getHibernateTempelete().delete(entity) 數(shù)據(jù)的時(shí)候 拋出了一個(gè)異常,異常信息是空值引用了一個(gè)非空值,意思就是說在刪除數(shù)據(jù)的時(shí)候ORM進(jìn)行Mapping 映射時(shí),將一個(gè)空值插入到了一個(gè)標(biāo)識(shí)為不能為空的屬性中. 經(jīng)過一段仔細(xì)的研究后發(fā)現(xiàn)hibernate 在進(jìn)行delete,update 操作的時(shí)候,必須將傳入的一個(gè)持久化Pojo對(duì)象,new 的對(duì)象是不行的, 需要在delete,update 時(shí) 加載持久化對(duì)象,所以我在加載的時(shí)候 ,選用了getHibernateTempelete.get(Entity.class,id)來獲取這一持久對(duì)象. 后來有人說需要在update,delete操作時(shí)推薦使用load(Entity.class,id) 方法.加載持久化對(duì)象,這樣可以在你緩存中讀取數(shù)據(jù). 這里我搜了一點(diǎn)資料,是關(guān)于 getHibernateTempelete.get(Entity.class,id)和getHibernateTempelete.load(Entity.class,id) 的區(qū)別 轉(zhuǎn)自 https://blog.csdn.net/iteye_18903/article/details/82135065 一、 get的用法 1 get(final Class entityClass, final Serializable id, final LockMode lockMode) 2 get(final String entityName, final Serializable id, final LockMode lockMode) 一般lockMode默認(rèn)為空,也就是說LockMode這個(gè)參數(shù)不寫 3 補(bǔ)充說明LockMode類: 該實(shí)例代表關(guān)系型數(shù)據(jù)庫(kù)表中一條記錄的鎖定方式,Hibernate的加鎖模式---包括 3.1 LockMode.NONE:無鎖機(jī)制 3.2 LockMode.WRITE:Hibernate在Insert和Update記錄的時(shí)候會(huì)自動(dòng)獲取 (注:不能在load的時(shí)候用,否則拋出異常) 3.3 LockMode.READ:直接從數(shù)據(jù)庫(kù)中讀數(shù)據(jù),繞過了Hibernate的Cache 3.4 LockMode.UPGRADE:通過select * from ta for update方法,可以將查詢結(jié)果中的記錄進(jìn)行update鎖定,及不允許其他進(jìn)行對(duì)這些記錄進(jìn)行修改, 3.5 LockMode.UPGRADE_NOWAIT:Oracle的特定實(shí)現(xiàn),利用Oracle的for update nowait子句實(shí)現(xiàn)加鎖 相對(duì)于upgrade 不想其他進(jìn)行進(jìn)入停頓狀態(tài),可以用nowait子句,直接返回操作異常信息,提示操作的記錄處于鎖定狀態(tài)不能進(jìn)行修改 二、load的用法 同get 三、get和load的區(qū)別 主要的地方: getHibernateTemplate.load() 存在延遲加載問題。 getHibernateTemplate.get() 不存在此問題,她是不采用lazy機(jī)制的。 1 當(dāng)記錄不存在時(shí)候,get方法返回null,load方法產(chǎn)生異常,即get()可以取空的數(shù)據(jù)集,但load()不行。 take a look at the Hibernate documentation (though I agree is not very explicit)--the HibernateTemplate is basically a wrapper around the native Hibernate API. get() will return null if an object is not found while load() will always return a non-null object which is a proxy. If the underlying object does not exist, the proxy will thrown ObjectNotFoundException. load() should be used when you are sure that the object exits while get() when you're not. 2 load方法可以返回實(shí)體的代理類,get方法則返回真是的實(shí)體類 3 load方法可以充分利用hibernate的內(nèi)部緩存和二級(jí)緩存中的現(xiàn)有數(shù)據(jù),而get方法僅僅在內(nèi)部緩存中 進(jìn)行數(shù)據(jù)查找,如果沒有發(fā)現(xiàn)數(shù)據(jù)則將越過二級(jí)緩存,直接調(diào)用SQL查詢數(shù)據(jù)庫(kù)。 4 也許別人把數(shù)據(jù)庫(kù)中的數(shù)據(jù)修改了,load如果在緩存中找到了數(shù)據(jù),則不會(huì)再訪問數(shù)據(jù)庫(kù),而get則會(huì) 總之對(duì)于get和load的根本區(qū)別,一句話,hibernate對(duì)于load方法認(rèn)為該數(shù)據(jù)在數(shù)據(jù)庫(kù)中一定存在,可以放心的使用代理來延遲加載,如果在 使用過程中發(fā)現(xiàn)了問題,就拋異常;而對(duì)于get方法,hibernate一定要獲取到真實(shí)的數(shù)據(jù),否則返回null。 轉(zhuǎn)自 https://blog.csdn.net/itough/article/details/20931671 |
|