hibernate多对多关联(六)

来源:互联网 发布:网络签约作家 编辑:程序博客网 时间:2024/05/21 17:46

多对多关联关系配置

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

publicclassUserimplements Serializable {

   privateIntegerid;

   privateStringname;

   privateIntegerage;

private Set<Role>roles;

 

publicclassRole { 

     privateintrid

     privateStringinfo;

 

 

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

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

            <generatorclass="native"/>

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

                </generator>-->

        </id>

        <setname="roles"table="user_role">

            <keycolumn="uid"></key>

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

        </set>

    </class>

 

 

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

        <idname="rid"column="rid"type="integer">

            <generatorclass="native"/>

        </id>

        <propertyname="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中添加

<setname="users"table="user_role">

            <keycolumn="rid"></key>

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

        </set>


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

0 0
原创粉丝点击