在使用hibernate作为数据持久层中配置many-to-one关系映射时发生的问题
//课程
public class Subject implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3;
private int subjectid;
private String subjectname;
private float hours;
private Grade grade;
}
//年级
public class Grade implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2L;
private int gradeId;
private String gradeName;
}
其中的关系是每个课程(N)只能适合于某一个年级(1)其关系映射是多对一的情况,在hibernate中是如下描述
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.futuremap.model">
<class name="Grade" table="grade" lazy="false" >
<id
column="GradeId"
name="GradeId"
type="integer"
>
<generator class="increment"/>
</id>
<property
column="GradeName"
length="50"
name="GradeName"
not-null="false"
type="string"
/>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.futuremap.model">
<class name="Subject" table="subject" lazy="false" >
<id
column="SubjectId"
name="SubjectId"
type="integer"
>
<generator class="increment" />
</id>
<property
column="SubjectName"
length="255"
name="SubjectName"
not-null="false"
type="string"
/>
<property
column="Hours"
length="12"
name="Hours"
not-null="false"
type="java.lang.Float"
/>
<many-to-one
name="Grade"
class="Grade"
column="GradeId"
/>
</class>
如果不添加lazy=false的话,返回grade对象是空的,如果加上就有值。最后查看帮助文档发现
lazy属性描述为是否采用延迟加载 .难怪不会出现