I have a simple application with a class GrandParent that has a Set<Parent>. I also have a class Child that inherits Parent. When I try to add Child-objects to the Set and then save to db with Hibernate it works for one object. But when I try to add a second Child nothing is added to the db (not event the GrandParent-object and the first Child). I have implemented equals() and hashcode() in the relevant classes. The Set really contains all inserted Child-objects (I have checked).
Hibernate version:
3.1
Mapping documents:
grandparent.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_test.GrandParent" table="grandparents">
<id name="id" type="long" unsaved-value="0">
<column name="grandparent_id" sql-type="integer" not-null="true"/>
<generator class="native"/>
</id>
<set name="children" lazy="false" inverse="true" cascade="all">
<key column="parent_id"/>
<one-to-many class="hibernate_test.Parent"/>
</set>
</class>
</hibernate-mapping>
parent.hbm.xmlCode:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_test.Parent" table="parents">
<id name="id" type="long" unsaved-value="0">
<column name="parent_id" sql-type="integer" not-null="true"/>
<generator class="native"/>
</id>
<discriminator column="discr"/>
<many-to-one name="parent" column="grandparent_id" not-null="false"/>
<property name="name"/>
<subclass name="hibernate_test.Child" extends="hibernate_tests.Parent" discriminator-value="child">
<property name="age"/>
</subclass>
</class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():Code:
Transaction tx = null;
try {
tx = getCurrentSession().beginTransaction();
Object o = getCurrentSession().save(object);
System.out.append("Adding "+object);
commitTransaction(tx);
return o;
} catch (Exception e) {
System.out.append(e.toString());
} finally {
releaseTransaction(tx);
}
return null;
Name and version of the database you are using:MySQL 4.1.18
The generated SQL (show_sql=true):Code:
Hibernate: insert into parents (grandparent_id, name, age, discr) values (?, ?, ?, 'child')
org.hibernate.exception.ConstraintViolationException: could not insert: [hibernate_test.Child]