Timo Ernst
Timo Ernst

Reputation: 15973

HibernateException: Foreign key may not be null

I have the following pretty simple many-to-one relationship between Person and their parents/children (which also are instances of Person again).

Person.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">
<!-- Generated 04.05.2011 15:02:31 by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
    <class name="test.Person" table="PERSONS">

        <id name="id" type="long" access="field">
            <column name="PERSON_ID" />
            <generator class="native" />
        </id>

        <bag name="children" table="PERSONS" lazy="false" inverse="true" cascade="all">
            <key column="PERSON_ID" not-null="false"></key>
            <one-to-many class="test.Person" />
        </bag>

        <many-to-one name="parent" column="PARENT_ID" not-null="false" />

    </class>
</hibernate-mapping>

Now, the problem in my case is that I have instances of Person which do not have parents (e.g. orphans).

If I try to persist these objects, I get:

java.sql.SQLException: null, message from server: "Column 'PARENT_ID' cannot be null"

If I set not-null="true" in the mapping file, I get:

org.hibernate.PropertyValueException: not-null property references a null or transient value: test.parent

What's the magic trick here?

Upvotes: 0

Views: 3698

Answers (1)

Anthony Accioly
Anthony Accioly

Reputation: 22461

Valmar, since you are getting a SQL Exception, probably your COLUMN 'PARENT_ID' have a not null constraint. Check your table DDL. What database are you using?

Upvotes: 1

Related Questions