单向一对多关系映射:
一个房间对应多个使用者,也就是Room實例知道User實例的存在,而User實例則沒有意識到Room實例。
用户表:
package onlyfun.caterpillar; public class User { private Long id; private String name; public User() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
在room类中,是直接把用户作为一个对象直接存进room表中,其中user对象的类型是Set
room类:
package onlyfun.caterpillar; import java.util.Set; public class Room { private Long id; private String address; private Set users; public Room() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; } public void addUser(User user) { users.add(user); } public void removeUser(User user) { users.remove(user); } }
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="onlyfun.caterpillar.User" table="user"> <id name="id" column="id"> <generator class="native"/> </id> <property name="name" column="name"/> </class> </hibernate-mapping>
使用<one-to- many>标签配置一对多:
Room.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="onlyfun.caterpillar.Room" table="room"> <id name="id" column="id"> <generator class="native"/> </id> <property name="address" column="address" type="java.lang.String"/> <set name="users" table="user" cascade="all"> <key column="room_id"/> <one-to-many class="onlyfun.caterpillar.User"/> </set> </class> </hibernate-mapping>
接著您可以如下儲存物件:
User user1 = new User();
user1.setName("bush");
User user2 = new User();
user2.setName("caterpillar");
User user3 = new User();
user3.setName("momor");
Room room1 = new Room();
room1.setUsers(new HashSet());
room1.setAddress("NTU-M8-419");
room1.addUser(user1);
room1.addUser(user2);
Room room2 = new Room();
room2.setUsers(new HashSet());
room2.setAddress("NTU-G3-302");
room2.addUser(user3);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(room1); // cascade 操作
session.save(room2);
tx.commit();
session.close();