inverse的意思是:相反、倒轉;相反的、倒轉的。 在hibernate xml映射配置文件裏面表示由那一方維護表關係。inverse="true"表示由對方維護表關係,inverse="false"則反之。示例以下:java
Member與MemberCard是一對多的關係:mysql
1. 關係由MemberCard維護。git
Member配置。Member.hbm.xmlsql
<set name="memberCards" inverse="true" cascade="save-update" lazy="true" table="member_card"> <key> <column name="member_id" not-null="true" /> </key> <one-to-many class="com.wss.lsl.hibernate.mysql.demo.xml.core.entity.MemberCard" /></set>
MemberCard配置。MemberCard.hbm.xmlsession
<many-to-one name="member" column="member_id" not-null="true" class="com.wss.lsl.hibernate.mysql.demo.xml.core.entity.Member" />
執行以下java代碼app
Member member = new Member(); member.setMemberName("張三"); Set<MemberCard> memberCards = new HashSet<MemberCard>(); MemberCard card1 = new MemberCard(); card1.setCardNo("1234567890"); MemberCard card2 = new MemberCard(); card2.setCardNo("1234567891"); MemberCard card3 = new MemberCard(); card3.setCardNo("1234567892"); // 由MemberCard維護關係,必須設置Member,否則插入外鍵時找不到member_id card1.setMember(member); card2.setMember(member); card3.setMember(member); memberCards.add(card1); memberCards.add(card2); memberCards.add(card3); member.setMemberCards(memberCards); session.save(member);
獲得的sql輸出以下:MemberCard在插入時,把外鍵也插入了。ui
Hibernate: insert into member (id, member_name) values (null, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?)
2. 關係由Member維護。.net
xml映射文件的配置大體相同,只是Member中的配置inverse="false", MemberCard中的<many-to-one not-null="true" .. /> not-null要設置成false。 先插入MemberCard,外鍵暫時爲null,後期再由Member update設置MemberCard的外鍵,因此not-null要容許爲null,否則執行不經過。 保存的java代碼和上面稍有不一樣,MemberCard不須要設置Member了。hibernate
Member member = new Member(); member.setMemberName("張三"); Set<MemberCard> memberCards = new HashSet<MemberCard>(); MemberCard card1 = new MemberCard(); card1.setCardNo("1234567890"); MemberCard card2 = new MemberCard(); card2.setCardNo("1234567891"); MemberCard card3 = new MemberCard(); card3.setCardNo("1234567892"); memberCards.add(card1); memberCards.add(card2); memberCards.add(card3); member.setMemberCards(memberCards); session.save(member);
獲得的sql輸出以下:多了幾條update語句。code
Hibernate: insert into member (id, member_name) values (null, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?) Hibernate: insert into member_card (id, card_no, member_id) values (null, ?, ?) Hibernate: update member_card set member_id=? where id=? Hibernate: update member_card set member_id=? where id=? Hibernate: update member_card set member_id=? where id=?
從一對多的關係維護中,不難看出由「多端」維護關係,效率要高。
更多參考hibernate demo