前面两篇文章《关联映射(一对多) (1)》、《关联映射(一对多) (2)》分别谈了“单向一对多关系”与“单向多对一关系”,双向一对多关系就是二者的组合。为了更好地提高执行效率,需要将“多”的一端设为主控方,就是将关联关系的维护工作交给“多”的一端。
以《关联映射(一对多) (2)》为基础,只要改动一下Room类即可。
· 修改Room类,仅仅是添加了关联User类的代码。
Room.java
package javamxj.hibernate.association.one2many;
import java.util.HashSet;
import java.util.Set;
/**
* @hibernate.class table = "T_Room"
*/
public class Room {
private Long id;
private String address;
private Set users = new HashSet();
/**
* @hibernate.id
*column="ID"
*generator-class="hilo"
*unsaved-value="null"
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @hibernate.property length = "24"
*/
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
/**
* @hibernate.collection-one-to-many
* class = "javamxj.hibernate.association.one2many.User"
* @hibernate.collection-key
* column = "Room_ID"
* @hibernate.set
* cascade = "all"
* table = "T_User"
* inverse = "true"
*/
public Set getUsers() {
return users;
}
public void setUsers(Set users) {
this.users = users;
}
}
这个类同《关联映射(一对多) (1)》中的Room类几乎完全一样,有一点不同在于多了inverse = "true",这样就将Room设置成了被控方,而将主控方交给了User。
· 然后同上面文章一样,生成映射文件,生成表,执行Demo,最后数据表中生成同上篇文章中相同的数据。
· 也可以修改Demo.java文件,让User设置关联关系,Room通过级联来更新User。
Demo.java
/*
* Hibernate - 关联(Association)映射(一对多)
* 创建日期 2005-4-27
* @author javamxj(分享java快乐)
* @link Blog: htpp://blog.csdn.net/javamxj/
* htpp://javamxj.mblogger.cn
*/
package javamxj.hibernate.association.one2many;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class Demo {
public static void main(String[] args) throws HibernateException {
Room room1 = new Room();
room1.setAddress("科研007");
Room room2 = new Room();
room2.setAddress("销售001");
User user1 = new User();
user1.setName("张三");
user1.setRoom(room1);
User user2 = new User();
user2.setName("李四");
user2.setRoom(room1);
User user3 = new User();
user3.setName("王二");
user3.setRoom(room2);
room1.getUsers().add(user1);
room1.getUsers().add(user2);
room2.getUsers().add(user3);
SessionFactory sf= new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(room1);
session.save(room2);
tx.commit();
session.close();
sf.close();
}
}