Hibernate annotation配置方式的MappedBy使用詳解說是使用詳解,其實是我自己做了一些簡單的試驗.如有說錯,請指正. Annotation方式的MappedBy其實就是xml方式的inverse http:///questions/10082434/mappedby-and-inverse-attributes-are-same 寫道 In case of one-one or one-many or many to one, the key will be stored in one of the entites. It does not make any sense to store it in 2 places. It essential tells hibernate that the key is at the other end of the relationship. So if there are entities A and B which have a one to one relationship, and you see the mappedBy attribute in A, then the foreign key (which points to A) is stored in B. 但是對于他們的行為 我一直不是很了解 hibernate里的doc解釋也不是很清楚: 寫道 inverse 映射屬性究竟表示什么呢?對于你和 Java 來說,一個雙向關聯(lián)僅僅是在兩端簡單地正確設置引用。然而,Hibernate 并沒有足夠的信息去正確地執(zhí)行 INSERT 和 UPDATE 語句(以避免違反數(shù)據(jù)庫約束),所以它需要一些幫助來正確的處理雙向關聯(lián)。把關聯(lián)的一端設置為 inverse 將告訴 Hibernate 忽略關聯(lián)的這一端,把這端看成是另外一端的一個鏡象(mirror) 其實簡單點說 就是MappedBy確定"維護關系"的一方,也僅僅是"維護關系"而已.其他的操作不影響. 實驗環(huán)境:hibernate 3.6.10.Final 實體類:User(多方) Classroom(一方) Many-to-One的測試
Java代碼:
Java代碼 :
從多方插入就不再累述了. 這里就試著從不維護關系的一方來插入: Java代碼:
這樣只有一條插入語句: Hibernate: insert into Classroom (cname) values (?) 為了更好地說明問題,我把以上一方的配置進行修改 加入了 cascade=CascadeType.ALL 同樣執(zhí)行以上代碼 顯示插入了兩條: Hibernate: insert into Classroom (cname) values (?) Hibernate: insert into User (cid, uname, upass) values (?, ?, ?) 但是查看數(shù)據(jù)庫就會發(fā)現(xiàn):
雖然插入了..但是外鍵卻沒有值 一方不維護關系就可以明顯的看出來, 但是一方的其他不影響關系的更新操作是沒有問題的: Java代碼:
執(zhí)行以上的代碼: 顯示: Hibernate: select classroom0_.cid as cid1_0_, classroom0_.cname as cname1_0_ from Classroom classroom0_ where classroom0_.cid=? Hibernate: select users0_.cid as cid1_1_, users0_.uid as uid1_, users0_.uid as uid0_0_, users0_.cid as cid0_0_, users0_.uname as uname0_0_, users0_.upass as upass0_0_ from User users0_ where users0_.cid=? cc Hibernate: update User set cid=?, uname=?, upass=? where uid=? 數(shù)據(jù)在數(shù)據(jù)庫里也被正常更新 這樣一番實驗坐下來就可以很清楚的感覺到 mappedBy只是確定了由誰來維護關系而已 其他的操作并不影響.
一般情況下 如果要讓兩方都可以維護關系 我自己是在OneToMany后寫JoinColumn 然后和ManyToOne里的外鍵列名取一樣的。 當然也可以不寫JoinColumn 來生成一個第三方表記錄關系 但這樣做沒什么必要 相同的關系會被存兩次. |
|
|
來自: wayne_liberary > 《技術博文》