I'm currently trying to setup a bidirectional many-to-one association and keep getting a constraint violation when I run my regression tests. Any thoughts on what I have done wrong would be appreciated. I'm using Hibernate (3.5.1-Final) with MySQL (5.1.35-community). I have isolated my problem to a test case with an entity A that references a single entity B while entity B references a collection of entity A's. The mappings for these are as follows
Code:
<hibernate-mapping package="ssss.domain">
<class name="A" table="A" >
<id name="id" column="A_ID" type="long">
<generator class="native"/>
</id>
<many-to-one name="b" column="B_ID" class="B" not-null="true"/>
</class>
</hibernate-mapping>
Code:
<hibernate-mapping package="ssss.domain">
<class name="B" table="B" >
<id name="id" column="B_ID" type="long">
<generator class="native"/>
</id>
<bag name="a" inverse="true">
<key column="A_ID" not-null="false"/>
<one-to-many class="A"/>
</bag>
</class>
</hibernate-mapping>
I'm running test in a Spring framework with transactions automatically inserted around each test. My test code is given below, the constraint violation happens when the save on the bean is called.
Code:
@Test
public void testBValue() {
final A bean = createInitialisedA();
final B value = createInitialisedB();
save(value);
bean.setB(value);
save(bean);
}
The constraint violation is
Code:
[WARN,JDBCExceptionReporter,main] SQL Error: 1452, SQLState: 23000
[ERROR,JDBCExceptionReporter,main] Cannot add or update a child row: a foreign key constraint fails (`ssss`.`a`, CONSTRAINT `FK41212E88BF` FOREIGN KEY (`A_ID`) REFERENCES `b` (`B_ID`))
I've tried looking at the schema that results and the constraint FK41212E88BF in the ddl, below, looks wrong, but I don't know what part of my mapping is causing it.
Code:
create table A (A_ID bigint not null auto_increment, B_ID bigint not null, primary key (A_ID))
create table B (B_ID bigint not null auto_increment, primary key (B_ID))
alter table A add index FK41212EFD1E (B_ID), add constraint FK41212EFD1E foreign key (B_ID) references B (B_ID)
alter table A add index FK41212E88BF (A_ID), add constraint FK41212E88BF foreign key (A_ID) references B (B_ID)