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

hibernate中两个级联表,一个student表和一个book表,student表中有主键id,是book表中的外键;在用Student的类无法得到set集
查询的代码
Session   session=bo.HibernateSessionFactory.getSession();
Session   session=bo.HibernateSessionFactory.getSession();

//查询每个同学所拥有的所有书x;
Query   query=session.createQuery( "from   Student ");
List   list=query.list();
for(int   i=0;i <list.size();i++)
{
Student   student=(Student)list.get(i);
System.out.println(student.getId());//到这里可以
Set   listbooks=student.getBooks();//出错
System.out.println(listbooks);
/*Iterator   it=listbooks.iterator();
while(it.hasNext())
{
Book   book=(Book)it.next();
System.out.println( "姓名     "+student.getName()+ "   书名         "+book.getName());
}*/
}


Book.hbm.xml文件
<?xml   version= "1.0 "   encoding= "utf-8 "?>
<!DOCTYPE   hibernate-mapping   PUBLIC   "-//Hibernate/Hibernate   Mapping   DTD   3.0//EN "
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
<!--  
        Mapping   file   autogenerated   by   MyEclipse   Persistence   Tools
-->
<hibernate-mapping>
        <class   name= "po.Book "   table= "BOOK "   schema= "DB2ADMIN ">
                <id   name= "id "   type= "java.lang.Integer ">
                        <column   name= "ID "   />
                        <generator   class= "native "   />
                </id>
                <many-to-one   name= "student "   class= "po.Student "   fetch= "select ">
                        <column   name= "SID "   />
                </many-to-one>
                <property   name= "name "   type= "java.lang.String ">
                        <column   name= "NAME "   length= "30 "   />
                </property>
        </class>
</hibernate-mapping>

Stuent.hbm.xml文件
<?xml   version= "1.0 "   encoding= "utf-8 "?>
<!DOCTYPE   hibernate-mapping   PUBLIC   "-//Hibernate/Hibernate   Mapping   DTD   3.0//EN "
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
<!--  
        Mapping   file   autogenerated   by   MyEclipse   Persistence   Tools
-->
<hibernate-mapping>
        <class   name= "po.Student "   table= "STUDENT "   schema= "DB2ADMIN "&