Reputation: 93
I have the class "Character" and the class "Faction". A character has a faction. A faction can be used by many characters. The factions get persisted when the character is persisted. When there is no more character referencing the faction I want to remove it from the database.
When I had an 1:1 relationship it was easy because I could just use
@Persistent(dependent = "true")
to have it removed when it's not needed anymore. But that's not possible anymore, because now there could be another character still needing the faction. So if I try to delete character1 and he's using the same faction as character2 I get the following exception:
java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'FACTION' caused a violation of foreign key constraint 'CHARACTER_FK1' for key (1). The statement has been rolled back.
I ONLY want the faction to be deleted when no more character is needing it. How can I do that?
Upvotes: 2
Views: 304
Reputation: 3482
It think the best solution is going to be on the database itself, not in Java. You want to put an ON DELETE trigger on Character that will take the current record (the one being deleted), look up its' Faction, then check the Character table for other records referencing the same Faction. If other records referencing that Faction exist, do nothing. If other records referencing that Faction don't exist, delete the Faction.
If you can't do this on the database server, then you could easily do the same as above in code instead. The benefit with putting it directly on the database is that you have the rule defined in one place where it will always be enforced, regardless of how many middle code layers you have between your users and the data.
Upvotes: 1