private Integer id;
private String name;
//一系列的setter.getter方法
@Override
public String toString() {
return "name of student: " + name;
}
}
private Integer id;
private String name;
private Set<Student> students;
//一系列的setter.getter方法
@Override
public String toString() {
return "name of class: " + name;
}
}
<id name="id" length="4">
<generator class="native"></generator>
</id>
<property name="name" length="10"></property>
</class>
<id name="id" length="4">
<generator class="native"></generator>
</id>
<property name="name" length="10"></property>
<!-- 配置集合属性 -->
<set name="students" cascade="save-update">
<!-- key的含义,指在另一端增加的外键指向本主键.
如果设置上属性not-null="true",表示该外键非空,则在由"一"的一端维护关系时,
可能导致插入数据异常PropertyValueException.
-->
<key column="class_id"></key>
<!--one-to-many含义,指出set集合中的元素类型,以供加载时使用 -->
<one-to-many class="com.sxt.hibernate.one2many.entity.Student"/>
</set>
</class>
Session session = HibernateUtils.getSession();
Transaction t = session.beginTransaction();
try {
/**
* 测试插入数据
*/
/*
* Student student1=new Student();
* student1.setName("奇隆");
*
* Student student2=new Student();
* student2.setName("有朋");
*
* Set<Student> students=new HashSet<Student>();
* students.add(student1);
* students.add(student2);
*
* Classes classes=new Classes();
* classes.setName("不一班");
* classes.setStudents(students);
* //存储不成功.报错:org.hibernate.TransientObjectException
* //因为此时student对象还没有持久化,classes引用了瞬时对象student1,student2
* session.save(classes);
*/
Student student1=new Student(); student1.setName("奇隆");
//session.save(student1);//先把student对象持久化
Student student2=new Student();
student2.setName("有朋");
//session.save(student2);
Set<Student> students=new HashSet<Student>();
students.add(student1);
students.add(student2);
Classes classes=new Classes();
classes.setName("不一班");
classes.setStudents(students);
//存储成功.sql语句如下:
/*
Hibernate: insert into sxt_hibernate_class (name, id) values (?, ?)
Hibernate: insert into sxt_hibernate_student (name, id) values (?, ?)
Hibernate: insert into sxt_hibernate_student (name, id) values (?, ?)
Hibernate: update sxt_hibernate_student set class_id=? where id=?
Hibernate: update sxt_hibernate_student set class_id=? where id=? */
//可见在存储class之后,发出两个update语句,把它的两个student对象的class_id更新了.
//这是因为关系由"一"的一端维护(即class维护关系).这显然会降低效率.
//所以对于一对多,我们一般把关系交给"多"的一端维护.
session.save(classes);
/**
* 测试加载数据
*/
/* Classes classes = (Classes) session.load(Classes.class, 3);
System.out.println(classes);
Set<Student> students = classes.getStudents();
for (Iterator<Student> stus = students.iterator(); stus.hasNext();) {
System.out.println(stus.next());
}*/
t.commit();
} catch (HibernateException e) {
e.printStackTrace();
t.rollback();
} finally {
HibernateUtils.closeSession(session);
}
}
}