hibernate多对多关联(六)

多对多关联关系配置

User和Role多对多关联关系,单向。User可以访问role。

publicclassUser implements Serializable {

   privateInteger id;

   privateString name;

   privateInteger age;

private Set<Role> roles;

 

publicclassRole { 

     privateintrid

     privateString info;

 

 

    <class name="org.hibernate.tutorial.domain.User"table="user">

        <id name="id"type="java.lang.Integer" column="id">

            <generator class="native" />

            <!-- <generator class="foreign" ><param name="property">card</param>

                </generator>-->

        </id>

        <set name="roles" table="user_role">

            <key column="uid"></key>

            <many-to-many class="org.hibernate.tutorial.domain.Role"column="rid"></many-to-many>

        </set>

    </class>

 

 

<class name="org.hibernate.tutorial.domain.Role"table="role">

        <id name="rid"column="rid" type="integer">

            <generator class="native"/>

        </id>

        <property name="info" column="info"type="string"/>

</class>

 

 

测试

User user = (User) session.load(User.class, new Integer(46));

//          Useruser = new User();

//          user.setAge(11);

//          user.setName("young");

           

            Roler = new Role();

            r.setInfo("guest");

//          Set<Role>s = new HashSet<Role>();

//          user.setRoles(s);

           

            user.getRoles().add(r);

            session.save(r);

            session.save(user);

 

sql语句

Hibernate: select user0_.id asid0_1_, user0_.name as name0_1_, user0_.age as age0_1_, card1_.id as id4_0_,card1_.info as info4_0_ from user user0_ left outer join card card1_ onuser0_.id=card1_.id where user0_.id=?

Hibernate: select roles0_.uid asuid1_, roles0_.rid as rid1_, role1_.rid as rid2_0_, role1_.info as info2_0_from user_role roles0_ left outer join role role1_ on roles0_.rid=role1_.ridwhere roles0_.uid=?

Hibernate: insert into role (info)values (?)

Hibernate: insert into user_role(uid, rid) values (?, ?)

 

多对多关联关系,双向配置

在上述基础上,在Role.hbm.xml中添加

<set name="users" table="user_role">

            <key column="rid"></key>

            <many-to-many class="org.hibernate.tutorial.domain.User"column="uid"></many-to-many>

        </set>


书上说多对多关联关系性能不佳,由于引入了中间表,一次都写需要反复次数的数据库查询,因此应该避免大量使用(或者避免使用)同时应该采取延迟加载,节约不必要的开销。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值