inverse的意思是:相反、倒转;相反的、倒转的。 在hibernate xml映射配置文件里面表示由那一方维护表关系。inverse="true"表示由对方维护表关系,inverse="false"则反之。示例如下:
Member与MemberCard是一对多的关系:
1. 关系由MemberCard维护。
Member配置。Member.hbm.xml
<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.xml
<many-to-one name="member" column="member_id" not-null="true" class="com.wss.lsl.hibernate.mysql.demo.xml.core.entity.Member" />
执行如下java代码
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在插入时,把外键也插入了。
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维护。
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了。
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语句。
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