假設Team和Student是1對多的關系,而student中只有team_id和name兩個屬性,我們可以不建立Student實體類,采用element的方式,由于bag可以允許重復,所以,在我們根據team刪除其下某一個student的時候,hibernate不知道具體要刪除哪一條數據,所以,只有講team下所有student全部刪除,然后再重新插入不應該刪除的數據,這樣會對效率有很大影響,針對這種情況,可以采用idbag標簽,在student中加一個字段cid來唯一標識每一個student
數據庫結構:
?


Pojo:
?































?Team.hbm.xml
?
























?
Hibernate.cfg.xml
?



































?
測試代碼:
?





















































?
運行結果:
Hibernate: select team0_.id as id0_, team0_.teamname as teamname0_ from teamIDBag team0_ where team0_.teamname='team1'
Hibernate: select students0_.team_id as team1_0_, students0_.name as name0_, students0_.cid as cid0_ from studentIDBag students0_ where students0_.team_id=?
Hibernate: delete from studentIDBag where cid=?
可以紅色部分,刪除student時是根據cid刪的,如果不使用idbag,則會出類似delete from studentIDBag where team_id=?的操作,然后會接著跟一個insert操作,來恢復本不應該刪除的數據
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
