参考:http://hi.baidu.com/ohaozy/blog/item/ed486a33bc83cf48ac4b5f75.html
下面是我调试过的代码
通过简单的例子说明这几个关系: 以下测试都是在mysql5下完成,数据库表是由hibernate.cfg.xml里配置了。 |
- 建类
Teacher.java
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
public String toString() {
return "Teacher:[teacherId=" + this.id + "/tteacherName="
+ this.teaName + "]";
}
}
Student.java
Student.hbm.xml
Teacher.hbm.xml
<set name="students" fetch="join" lazy="false">
<!--
<set name="students">
-->
<key column="teacherId"></key>
<!--
这里的column="teacherId" 是指明了在student表里有一个teacherId的列名,是指向teacher表的外键
-->
<one-to-many class="Student" />
</set>
</class>
</hibernate-mapping>
hibernate.cfg.xml
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Test.java
List list = session.createQuery("from Teacher t where t.id=1").list();
//List list = session.createQuery("from Teacher t left join fetch t.students where t.id=1").list();
Teacher t = (Teacher)list.get(0);
System.out.println(t);//
System.out.println(t.getStudents().iterator().next());
for(int i=0;i<list.size();i++)
{
Teacher tt = (Teacher)list.get(i);
System.out.println(tt);//
System.out.println(tt.getStudents().iterator().next());
}
/*//未明白什么意思,和session有什么关系呢?
* 上面这句话放在session结束前,student在用到的时候将会自动被查询出来,否则查询语句应改为:
* from Teacher t left join fetch t.students where t.id=1
* 或者设置teacher.hbm.xml里的set属性,加上:fetch="join" lazy="false":
* <set name="students" fetch="join" lazy="false">
* <key column="teacherId"></key> <one-to-many class="model.Student"/> </set>
*/
tx.commit();
session.close();
sf.close();
}
}