Hibernate映射一对多单向关联(之二)
2010-04-28 16:25
295 查看
在Hibernate映射一对多单向关联(之一)的基础上,看一下映射一对多单向关联中检索数据的情况。
我们要查询student表中某个学生对应的在sc表中的课程情况,一种方式就是直接将要查询的学生的学号(sno)set到Sc的对象上,直接通过Sc的对象检索sc表查得所需要的记录。
另一种通过配置的一对多关联,使用Student对象获取Sc对象。
测试程序如下:
运行结果如下所示:
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中的记录迭代出来。
我们要查询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中的记录迭代出来。
相关文章推荐
- 【hibernate】关联映射那些事(二)--单向1-N映射和单向N-N映射
- Hibernate一对一主键关联映射(单向)
- Hibernate 映射关系 ---One2Many单向关联
- hibernate实现一对一单向关联映射
- hibernate之关于一对一单向,双向关联映射
- 一口一口吃掉Hibernate(四)——多对一单向关联映射
- Hibernate实体关系映射:单向主键一对一关联
- 一口一口吃掉Hibernate(五)——一对多单向关联映射
- Hibernate关联映射 --- 多对多实例分析(单向关联)
- 【hibernate】之关于一对一单向,双向关联映射
- Hibernate(四):Hibernate映射——多对一单向关联映射
- Hibernate之对象关系映射01一对一单向关联
- 【Hibernate步步为营】--单向关联一对一映射
- 【hibernate框架】关系映射之一对一单向外键关联(XML实现)
- hibernate-关系映射(一对多单向关联)-9
- ORM框架Hibernate (四) 一对一单向、双向关联映射
- 【SSH】——Hibernate(4)关联映射之单向映射
- Hibernate关系映射级别注解(一对一单向外键关联)
- hibernate单向一对多关联映射(one-to-many)XML与注解版
- Hibernate关系映射(单向关联)