not-null属性引用null或transient值:in.dao.Teacher.address

时间:2014-11-15 12:50:07

标签: hibernate

当我运行这个应用程序时,它给出了像org.hibernate.PropertyValueException这样的异常:not-null属性引用了一个null或瞬态值:in.dao.Teacher.address,可以在下面帮助我的代码

Teacher.java

package in.dao;

public class Teacher实现了java.io.Serializable {

 private Integer tid;
 private Address address;
 private String teachername;

public Teacher() {
}

public Teacher(Address address, String teachername) {
   this.address = address;
   this.teachername = teachername;
}

public Integer getTid() {
    return this.tid;
}

public void setTid(Integer tid) {
    this.tid = tid;
}
public Address getAddress() {
    return this.address;
}

public void setAddress(Address address) {
    this.address = address;
}
public String getTeachername() {
    return this.teachername;
}

public void setTeachername(String teachername) {
    this.teachername = teachername;
}

}

Teacher.hbm.xml

<hibernate-mapping>
    <class name="in.dao.Teacher" table="teacher" catalog="sample">
        <id name="tid" type="java.lang.Integer">
            <column name="tid" />
            <generator class="identity" />
        </id>
        <many-to-one name="address" class="in.dao.Address" fetch="select">
            <column name="locationid" not-null="true" />
        </many-to-one>
        <property name="teachername" type="string">
            <column name="teachername" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:0)

当您保存Teacher实体时,它可能引用尚未保存的地址实体。

您可以先保存地址并将保存的地址实例设置为教师,然后再保存,例如:

Address mergedAddress = session.merge(address);
teacher.setAddress(mergedAddress);
session.merge(teacher);

或者您可以在MERGE属性上将Cascade设置为Address,以便Hibernate在合并Teacher实体之前先合并地址。