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