日期:2014-05-19  浏览次数:20772 次

HQL查询问题
hiberinate 自动配置,主表Student和Course,从表Studcourse。
测试代码如下:
List<Student> list = session.createQuery("from Student ").list();
for(Student s: list){
//System.out.println(s.getSname()+"选择了"+s.getStudcourses().size()+"门课");
if(s.getStudcourses().size()==0){//此处获取不到关联对象
System.out.println(s.getSname()+"没有选课");
}else{
Set<Studcourse> sets = s.getStudcourses();
for(Studcourse sc : sets){
System.out.println(s.getSaddress()+"选了"+sc.getCourse().getCname());
}
}
}
结果总是答应没有选课,不是说查询一个表的全部信息"from Student ",可以封装成一个对象,然后可以通过主外键关系,获取关联信息吗?
s.getStudcourses().size()==0为什么总是成立呢?就是不能获得从表Studcourses的数据,查询结果为0.
生成的SQL语句如下:
Hibernate: select student0_.SID as SID0_, student0_.SNAME as SNAME0_, student0_.SSEX as SSEX0_, student0_.SDEPT as SDEPT0_, student0_.SAGE as SAGE0_, student0_.SADDRESS as SADDRESS0_ from SCOTT.STUDENT student0_
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
林青霞没有选课
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
刘德华没有选课
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
成龙没有选课
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
林可欣没有选课
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
周华健没有选课
Hibernate: select studcourse0_.SID as SID0_1_, studcourse0_.STUCOURSEID as STUCOURS1_1_, studcourse0_.STUCOURSEID as STUCOURS1_2_0_, studcourse0_.SID as SID2_0_, studcourse0_.CID as CID2_0_, studcourse0_.GRADE as GRADE2_0_ from SCOTT.STUDCOURSE studcourse0_ where studcourse0_.SID=?
周润发没有选课

------解决方案--------------------
主外键关系没有配置吧
------解决方案--------------------
你的Student表和Course表之间的关系进行了配置吗?
你可以从数据库中查到Student的数据,而没有查到关联的Course数据
证明这两个表之间的主外键关系你没有配置。
检查你的数据库和你的配置文件及相关的实体类,看是否配置正确。
------解决方案--------------------
看看延迟加载