SQL(数据库使用的MySQL):
CREATE TABLE room (
ROOM_ID int NOT NULL auto_increment,
ADDRESS varchar(32) NOT NULL default '',
PRIMARY KEY (ROOM_ID)
) TYPE=INNODB;
CREATE TABLE user (
USER_ID int NOT NULL auto_increment,
NAME varchar(16) NOT NULL default '',
ROOM_ID int NOT NULL default '',
INDEX (ROOM_ID),
FOREIGN KEY (ROOM_ID) REFERENCES Room(ROOM_ID),
PRIMARY KEY (USER_ID)
) TYPE=INNODB;
User.java
package ivan.hibernate.one2many;
public class User {
private long id;
private String name;
private Room room;
...
}
User.hbm.xml
<hibernate-mapping>
<class name="ivan.hibernate.one2many.User" table="USER">
<id name="id" column="USER_ID" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>
<many-to-one name="room"
column="ROOM_ID"
class="ivan.hibernate.one2many.Room"/>
</class>
</hibernate-mapping>
Room.java
package ivan.hibernate.one2many;
public class Room {
private long id;
private String address;
private Set users = new HashSet();
...
}
Room.hbm.xml
<hibernate-mapping>
<class name="ivan.hibernate.one2many.Room" table="ROOM">
<id name="id" column="ROOM_ID" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="address" type="string"/>
<set name="users" table="USER" inverse="true" cascade="all">
<key column="ROOM_ID"/>
<one-to-many class="ivan.hibernate.one2many.User"/>
</set>
</class>
</hibernate-mapping>
//注意这里需要设定 inverse=true。
Test.java
public class Test {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Room room = new Room();
room.setAddress("China-10-911");
User user1 = new User();
user1.setName("ivan");
User user2 = new User();
user2.setName("mada");
user1.setRoom(room);
user2.setRoom(room);
room.getUsers().add(user1);
room.getUsers().add(user2);
Session session = sessionFactory.openSession();
Transaction tx= session.beginTransaction();
session.save(room);
tx.commit();
session.close();
sessionFactory.close();
}
}