I am a bit of a hibernate newbie trying to figure out one thing.
I have a standard bidirectional many-to-many association between a user and a device object. I followed the manual for how to do this. When I delete the entry on the inverse end of my association (the device), I get a constraint violation.
The associations of my mapping file look like this:
User:
...
<set name="devices" table="symUsersDevices" lazy="true" inverse="false" cascade="none"
>
<key column = "UserKey"/>
<many-to-many class="com.siemens.symphonia.domain.po.DevicePO"
column="DeviceKey"
outer-join="auto"
/>
</set>
...
Device:
...
<set name="users" table="symUsersDevices" lazy="true" cascade="none" inverse="true">
<key column="DeviceKey"/>
<many-to-many column="UserKey" class="com.siemens.symphonia.domain.po.UserPO" outer-join="true"/>
</set>
...
Code:
Session session=sessionFactory.openSession();
session.delete(device);
session.flush();
session.close();
On the DB level, the association is realized via a join table generated by the schema generator. Obviously, from the traces, Hibernate only deletes the affected row in the device table but leaves the join table intact. The join table in MySQL looks like this:
create table UsersDevices (
UserKey varchar(32) not null,
DeviceKey varchar(32) not null,
primary key (UserKey, DeviceKey)
) type=InnoDB;
alter table UsersDevices
add index FKEFB27E1CD3E432AA (DeviceKey),
add constraint FKEFB27E1CD3E432AA
foreign key (DeviceKey)
references Devices (UUIDKey);
alter table UsersDevices
add index FKEFB27E1CFF5B2C4A (UserKey),
add constraint FKEFB27E1CFF5B2C4A
foreign key (UserKey)
references Users (UUIDKey);
It looks like this causes the constraint violation.
Now the question is: how can I avoid this? Do I have to walk through all users of the doomed device and remove the device from them and then update them (which would be rather tedious)?
On the DB level, I would solve this with on cascade delete and set null constraints but alas, Hibernate does not do that.
Thanks for your help.
|