Posted on 2009-07-22 11:13
leekiang 閱讀(2446)
評論(0) 編輯 收藏 所屬分類:
hibernate
[org.hibernate.event.def.AbstractFlushingEventListener] - Could not synchronize database state with session
org.hibernate.HibernateException: Unexpected row count: 0 expected: 1
?? ?at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:32)
?? ?先用對象操作得到Person p = get(Person.class,35);
?? ?直連得到connection,執行delete person where id=35
?? ?
?? ?事務提交前hibernate會對對象進行檢查,看屬性是否有變化,如果有變化就會執行update操作。
?? ?事務方法內既有對象操作,又有sql時,往往sql先執行,
?? ?id=35的記錄已經被刪了,再執行update 35時就會報那個臭名昭著的HibernateException: Unexpected row count: 0 expected: 1,不能同步數據庫狀態
?? ?為什么有的記錄刪除時會update,有的卻沒有?開始一直沒找到原因,因為update語句太長了,
?? ?后來靈機一動,在映射里加了dynamic-update="true",update語句變成了可愛的update Person set zd=? where ID=?
?? ?一查AbstractPerson,發現getZd()被修改了:
?? ??? ?public String getZd() {
?? ??? ?if (zd != null)
?? ??? ??? ?return zd;
?? ??? ?else
?? ??? ??? ?return "";
?? ??? }
??? 這樣凡是zd為null的記錄,刪除時都會報錯。
?? ?
?? ?總結:(1)HQL和sql共用時要小心,一不小心就出現數據不同步,有空看看事務的處理
?? ?????? (2)映射的類里的get方法不要隨便修改