如题,myeclipse+hibernate+sql server2008调试的时候出了些问题,蛮久了。
数据库表,t_student(sid,bid,sname)t_banji(bid,room) 关系是一个班级有多个学生。没有设置主键
po.Student ,po.Banji Banji :private String bid;
private String room; private Set students; Student :private String sid; private String bid;
private String sname; private Banji banji; 对应属性有get/set函数。映射文件Banji.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="po.Banji" table="t_banji">
<id name="bid" column="bid">
<generator class="assigned"/>
</id>
<property name="room" column="room"/>
<set name="students"
table="t_student"
lazy="false"
cascade="all"
inverse="true"
>
<key column="bid"></key>
<one-to-many class="po.Student"/>
</set>
</class>
</hibernate-mapping>
映射文件Sutdent.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="po.Student" table="t_student">
<id name="sid" column="sid">
<generator class="assigned"/>
</id>
<property name="bid" column="bid"/>
<property name="sname" column="sname"/>
<many-to-one name="banji" class="po.Banji" insert="false"
update="false" cascade="none" column="bid"/>
</class>
</hibernate-mapping>
以上是配置,现在是测试, 查询班级得到对应的学生,代码如下:
public class One2Many {
public static void main(String []args)
{
Session session=util.HibernateSessionFactory.getSession();
//查询班级知道对应的学生
Banji banji=(Banji)session.get(Banji.class, "11001");
Set set=banji.getStudents();
Iterator ite=set.iterator();
System.out.println(banji.getBid());
if(!ite.hasNext())
{
System.out.println("null");
}
while(ite.hasNext())
{
Student stu=(Student)ite.next();
System.out.println(stu.getSname());
}
util.HibernateSessionFactory.closeSession();
}
}
运行:结果是.11001 null
底层SQL语句是:Hibernate: select banji0_.bid as bid0_0_, banji0_.room as room0_0_ from t_banji banji0_ where banji0_.bid=?
Hibernate: select students0_.bid as bid1_, students0_.sid as sid1_, students0_.sid as sid1_0_, students0_.bid as bid1_0_, students0_.sname as sname1_0_ from t_student students0_ where students0_.bid=?
问题是:查询班级,对应学生显示不出来。请教各大神原因。
hibernate一对多间关联
------解决方案--------------------
排除法:注释掉查询语句,写个hql语句来查询,如果能查到,说明是你查询语句的问题;若查不到,看看数据库有没有数据,事务有没有提交(很可能是这个原因)。
------解决方案--------------------
我所说的这个事务提交是指的数据库事务提交,不是在代码层的事务提交。