您的位置:首页 > 其它

Hibernate映射一对多单向关联(之二)

2010-04-28 16:25 295 查看
在Hibernate映射一对多单向关联(之一)的基础上,看一下映射一对多单向关联中检索数据的情况。

我们要查询student表中某个学生对应的在sc表中的课程情况,一种方式就是直接将要查询的学生的学号(sno)set到Sc的对象上,直接通过Sc的对象检索sc表查得所需要的记录。

另一种通过配置的一对多关联,使用Student对象获取Sc对象。

测试程序如下:

package org.shirdrn.test;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.shirdrn.entity.Sc;
import org.shirdrn.entity.Student;

public class MyTest2
{
public static void main(String[] args)
{
Session session = HibernateSessionFactory.getSession();
try
{
Criteria c = session.createCriteria(Student.class);
c.add(Restrictions.eq("sno", "200802001"));
List list = c.list();
Student stu = (Student) list.get(0);
Set hsSet = stu.getScs();

Iterator it = hsSet.iterator();
while (it.hasNext())
{
Sc sc = (Sc) it.next();
System.out.println(":" + sc.getSno() + "," + sc.getCno() + ","
+ sc.getCname());
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
HibernateSessionFactory.closeSession();
}
}
}


运行结果如下所示:

Hibernate: select this_.sno as sno0_, this_.sname as sname0_0_, this_.dept as dept0_0_ from student this_ where this_.sno=?
Hibernate: select scs0_.sno as sno1_, scs0_.cno as cno1_, scs0_.sno as sno0_, scs0_.cno as cno0_, scs0_.cname as cname4_0_, scs0_.score as score4_0_ from sc scs0_ where scs0_.sno=?
:200802001 ,CS-003 ,数据仓库
:200802001 ,CS-002 ,搜索引擎
:200802001 ,CS-001 ,数据挖掘

可见,我们只使用了查询student表,但是在查询的时候,根据配置的映射关系,也检索了sc表,所以可以直接通过Student对象获取Sc的对象(注意,是一个Set集合)。然后,就可以使用Iterator将HashSet中的记录迭代出来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: