Hibernate 多對多的插入

2021-10-14 08:52:04 字數 1228 閱讀 3283

可能會遇到的問題

1.出現entry 「xx-***」 key is private

這個問題是由於插入關聯表中的資料並沒有在已有表中持久化的原因

比如說 student teacher student_teacher三張表 student和teacher多對多 student_teacher為中間表

如果寫new teacher 或者new student 進行關聯 就會出錯

只能從現有表中查詢(使用hql查詢語句或其他)找現有的已經持久化的資料 才能進行關聯

2.出現主鍵對應錯誤

這是由於雙向儲存的原因

session session = hibernateutil.

getsessionobject()

; transaction tc = session.

begintransaction()

; string hql =

"from com.example.demo.entities.address where id = '4028208176e7725a0176e77269b10001'"

; address ad =

(address) session.

createquery

(hql)

.uniqueresult()

; string hql2 =

"from com.example.demo.entities.testperson where id = '4028208176e7725a0176e77269570000'"

; testperson ts =

(testperson) session.

createquery

(hql2)

.uniqueresult()

; system.out.

println

(ad)

; ts.

getaddresses()

.add

(ad)

;// ad.getpersonset().add(ts);

tc.commit()

;

如果即寫了

ts.getaddresses().add(ad);

又寫了ad.getpersonset().add(ts);

就會報錯 寫乙個即可

hibernate的多對多

近日工作中遇到多對多,以前未曾用過hibernate,這次也算是摸著石頭過河。之前試驗了級聯的cascadetype.all,卻發現當刪除部門表的時候,中間表資料刪除了,結果將人員表相關聯的資料也全部刪除了。後來將級聯改為cascadetype.persist,cascadetype.merge,倒...

hibernate的多對多

1.herbernate一對多自關聯 樹形選單查詢可能出現的問題 當載入一級節點的時候沒問題 強制載入 載入二級載入時候,由於設定了強制載入,同樣可以載入出所有的二級節點。沒問題 載入 節點時,這是session關閉了,並且預設採用的是懶載入 許可權選單載入有兩種方式 1 一次性將資料庫表中的資料全...

hibernate的多對多

多對多關聯是hibernate中一種比較特殊的關聯,它需要借助中間表來完成多對多資訊的儲存。多對多關聯只有雙向關聯。資料庫的多對多 資料庫中不能直接對映多對多 處理 建立乙個橋接表 中間表 將乙個多對多關係轉換成兩個一對多。hibernate的多對多 hibernate可以直接對映多對多關聯關係 看...