今天我在hibernate 進行 getHibernateTempelete().delete(entity) 數(shù)據(jù)的時候 拋出了一個異常,異常信息是空值引用了一個非空值,意思就是說在刪除數(shù)據(jù)的時候ORM進行Mapping 映射時,將一個空值插入到了一個標識為不能為空的屬性中. 經(jīng)過一段仔細的研究后發(fā)現(xiàn)hibernate 在進行delete,update 操作的時候,必須將傳入的一個持久化Pojo對象,new 的對象是不行的, 需要在delete,update 時 加載持久化對象,所以我在加載的時候 ,選用了getHibernateTempelete.get(Entity.class,id)來獲取這一持久對象. 后來有人說需要在update,delete操作時推薦使用load(Entity.class,id) 方法.加載持久化對象,這樣可以在你緩存中讀取數(shù)據(jù). 這里我搜了一點資料,是關于 getHibernateTempelete.get(Entity.class,id)和getHibernateTempelete.load(Entity.class,id) 的區(qū)別 轉自 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默認為空,也就是說LockMode這個參數(shù)不寫 3 補充說明LockMode類: 該實例代表關系型數(shù)據(jù)庫表中一條記錄的鎖定方式,Hibernate的加鎖模式---包括 3.1 LockMode.NONE:無鎖機制 3.2 LockMode.WRITE:Hibernate在Insert和Update記錄的時候會自動獲取 (注:不能在load的時候用,否則拋出異常) 3.3 LockMode.READ:直接從數(shù)據(jù)庫中讀數(shù)據(jù),繞過了Hibernate的Cache 3.4 LockMode.UPGRADE:通過select * from ta for update方法,可以將查詢結果中的記錄進行update鎖定,及不允許其他進行對這些記錄進行修改, 3.5 LockMode.UPGRADE_NOWAIT:Oracle的特定實現(xiàn),利用Oracle的for update nowait子句實現(xiàn)加鎖 相對于upgrade 不想其他進行進入停頓狀態(tài),可以用nowait子句,直接返回操作異常信息,提示操作的記錄處于鎖定狀態(tài)不能進行修改 二、load的用法 同get 三、get和load的區(qū)別 主要的地方: getHibernateTemplate.load() 存在延遲加載問題。 getHibernateTemplate.get() 不存在此問題,她是不采用lazy機制的。 1 當記錄不存在時候,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方法可以返回實體的代理類,get方法則返回真是的實體類 3 load方法可以充分利用hibernate的內(nèi)部緩存和二級緩存中的現(xiàn)有數(shù)據(jù),而get方法僅僅在內(nèi)部緩存中 進行數(shù)據(jù)查找,如果沒有發(fā)現(xiàn)數(shù)據(jù)則將越過二級緩存,直接調(diào)用SQL查詢數(shù)據(jù)庫。 4 也許別人把數(shù)據(jù)庫中的數(shù)據(jù)修改了,load如果在緩存中找到了數(shù)據(jù),則不會再訪問數(shù)據(jù)庫,而get則會 總之對于get和load的根本區(qū)別,一句話,hibernate對于load方法認為該數(shù)據(jù)在數(shù)據(jù)庫中一定存在,可以放心的使用代理來延遲加載,如果在 使用過程中發(fā)現(xiàn)了問題,就拋異常;而對于get方法,hibernate一定要獲取到真實的數(shù)據(jù),否則返回null。 轉自 https://blog.csdn.net/itough/article/details/20931671 |
|
來自: 一本正經(jīng)地胡鬧 > 《框架》