一对多关系
one的一方使用Set保存它所对应的many的一方的多个数据。使用set因为数据库记录也是没有重复的,Set当然也是没有重复的。
Hibernate有一个有趣的地方,可以查询得到类,然后做修改,最后session.beginTransaction().commit();就能自动把对类的更新固化到数据库。
当然查询就不必开始事务。
另外,级联删除只需要在one的一方的mapping文件加上cascade="all" 详见下面的配置文件
下面贴几个重要文件:
1、Teacher.java
package com.learn.po;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import com.learn.dao.HibernateUtil;
public class Teacher {
private int teacherid;
private String nm;
private Set<Student> sss = new HashSet<Student>();
public String getNm() {
return nm;
}
public Set<Student> getSss() {
return sss;
}
public void setSss(Set<Student> sss) {
this.sss = sss;
}
public void setNm(String nm) {
this.nm = nm;
}
public int getTeacherid() {
return teacherid;
}
public void setTeacherid(int teacherid) {
this.teacherid = teacherid;
}
public static void getQuery1(){
Session session = HibernateUtil.getSessionFactory().openSession();
/*仅仅对Teacher查询还没有查Teacher对应的Student*/
Teacher t = (Teacher)session.get(Teacher.class, 3);
System.out.println(t.getNm());
/*以下涉及了多的一方 所以加上一次对Sudent的查询并存到set*/
System.out.println(t.getSss().size());
Set<Student>ss = t.getSss();
for (Iterator iterator = ss.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.println(student.getNm());
}
session.close();
}
public static void changeTeacher(){
Session session = HibernateUtil.getSessionFactory().openSession();
Teacher t1 = (Teacher) session.get(Teacher.class, 1);
Teacher t2 = (Teacher) session.get(Teacher.class, 2);
Student s = (Student) session.get(Student.class, 4);
//System.out.println(s.getNm());
t2.getSss().remove(s);
t1.getSss().add(s);
session.beginTransaction().commit();
}
public static void deleteCascade(){
/*先删除该老师的所有学生,再删除这个老师*/
//因为在配置文件里面cascade="all"所以可以级联删除
Session session = HibernateUtil.getSessionFactory().openSession();
Teacher t1 = (Teacher) session.get(Teacher.class, 1);
session.delete(t1);
session.beginTransaction().commit();
}
public static void main(String args[]){
//getQuery1();
//changeTeacher();
//deleteCascade();
}
}
2、Teacher映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="com.learn.po">
<class name="Teacher" table="teacher" lazy="true">
<id name="teacherid">
<generator class="identity"></generator>
</id>
<property name="nm"></property>
<set name="sss" cascade="all">
<!-- 这里的key表示作为外键的属性,如果该表的多个属性都是作为外键,那么下面多个key -->
<key column="teacherid"></key>
<!-- 这里的class是 多 的一方 -->
<one-to-many class="Student" />
</set>
</class>
</hibernate-mapping>