日期:2014-05-17  浏览次数:20652 次

关于Hibernate子类没有自动查询的问题
本帖最后由 dut_singer 于 2013-12-12 14:30:48 编辑
用Struts2+Hibernate做web应用,两个实体类Error和User,N->1映射
主要代码如下:Error.hbm.xml
		
<class name="Error" table="error_table">
<id name="error_id" column="error_id">
<generator class="identity"/>
</id>
<property name="report_time" type="java.util.Date"/>
<property name="report_user" type="java.lang.String"/>
<property name="report_dep" type="java.lang.String"/>
<property name="error_show_des" type="java.lang.String"/>
<property name="level" type="java.lang.Integer"/>
<property name="report_status" type="java.lang.Integer"/>
<!-- 到User表的外键,N->1 -->
<many-to-one name="user" class="User">
<column name="userid"></column>
</many-to-one>
<many-to-one name="platform" class="Platform">
<column name="platform_id"></column>
</many-to-one>
</class>

User.hbm.xml

<class name="User" table="user_table">
<id name="userid">
<generator class="identity"/>
</id>
<property name="username"/>
<property name="password"/>
<property name="name"/>
<property name="birthday"/>
<property name="email"/>
<property name="cellphone"/>
<!-- dep_id 是 user中的属性,columnid应该是外键 -->
<many-to-one name="dep" cascade="all" class="Department" column="dep_id" />
</class>

显示结果action

this.setError((Error)sess.get(Error.class,error.getError_id()));

显示查询结果jsp

<td>记录人</td><td><label><s:property value="%{error.user.username}"/></label> </td></tr>

只写了主要的代码,不知道能说明白不,
现在jsp中取不到username,但如果在action中,加入

System.out.println(error.getUser().getUsername());

jsp就能取到username了,这是为啥?父类中定义的子类还需要显示的查询一下,才能获取子类数据吗?

------解决方案--------------------
我感觉好像跟延迟加载有关,可能你取到 error时,他的user还没实际加载,到jsp页面时,读取这个error的session已经关闭了,就读不出user了