Hibernate version:
3.2.2 GA
Mapping documents:
Code:
<class name="Person" table="PERSON">
<id name="id" column="id" type="long" unsaved-value="0">
<generator class="native" />
</id>
<property name="name" />
<property name="color" />
<many-to-one
cascade="all"
name="attributes"
column="attributesId"
unique="false"
/>
</class>
<class name="Attributes" table="ATTRIBUTES">
<id name="id" column="id" type="long" unsaved-value="0">
<generator class="native" />
</id>
<property name="hairColor" />
<property name="eyeColor" />
<set name="people" inverse="true">
<key column="attributesId" />
<one-to-many class="Person"/>
</set>
</class>
Full stack trace of any exception that occurs:
Cannot delete or update a parent row: a foreign key constraint fails (`hib_test/person`, CONSTRAINT `FK8C768F554CCEF60C` FOREIGN KEY (`attributesId`) REFERENCES `attributes` (`id`))
Name and version of the database you are using:
MySQL5.0
The generated SQL (show_sql=true):
select attributes0_.id as id2_0_, attributes0_.hairColor as hairColor2_0_, attributes0_.eyeColor as eyeColor2_0_ from ATTRIBUTES attributes0_ where attributes0_.id=?
delete from ATTRIBUTES where id=?
The Scenario
I have a one-to-many relationship between Attributes and Person.
Attributes {
private Set<Person> people;
}
Person {
private Attributes attributes;
}
In my test case, I create a Person p and a linked Attributes a.
In a new transaction, I delete the attributes:
Attributes attributes = getHibernateTemplate().get(Attributes.class,id);
getHibernateTemplate().delete(attributes);
This generates the two SQL statements above, but fails to null out the foreign key (attributesId) for all Person records that may point to that Attributes that is being deleted.
Is there a way that Hibernate can automate this? I don't want to explicitly have to null out that foreign key every time I delete an Attributes, if possible.
I would like to see something like:
select attributes0_.id as id2_0_, attributes0_.hairColor as hairColor2_0_, attributes0_.eyeColor as eyeColor2_0_ from ATTRIBUTES attributes0_ where attributes0_.id=?
update PERSON set attributeId = NULL where attributeId = ?
delete from ATTRIBUTES where id=?
Many thanks for any help.