Reputation: 3244
I have a two classes, Service and Customer, with a many-to-one association from Service to Customer. I want to delete a Customer and any Service that references it. I'm using JPA as the ORM (with Hibernate underneath) attached to a PostgreSQL db.
It'd be great if I could define the association in such a way that deleting the Customer would cascade to the Services that reference it. But, and maybe I'm misunderstanding something, since the association is defined using @ManyToOne in Service the operations would cascade from Service to Customer but not the other way around?
So without the cascading delete, I set out to simply remove all Services that reference the Customer. Seemed easy enough except JPA/Hibernate wants to batch the deletes up and executes them in the wrong order! My code basically queries the Services that reference the Customer, calls entityManager.remove() on each, and then calls entityManager.remove() on the Customer. But when I flush it, I get an exception that the delete from Customer failed due to the foreign key constraint.
Do I really need to try to commit the delete from Service before the delete from Customer? I'd rather not as my transactions are container managed and it'd be a pain in the neck to make it commit.
Thanks, Andy
Upvotes: 0
Views: 4376
Reputation: 3244
I was wrong about the order. They were executed in the right order but the issue turned out to be yet another foreign key constraint that was previously unknown and causing the transaction to fail. It seems like the original approach should work fine as long as the code accounts for all constraints.
Upvotes: 0
Reputation: 96570
Personally, I would rethink your process. I don't believe customer data should be deleted ever. They should be marked as inactive but deleting them and the associated records can often cause you to lose information that you need to for historical reporting or accounting purposes.
Upvotes: 0
Reputation: 27224
Manually managing the constrained relationships is probably not a good idea, specially given that it is a very straightforward and standard type of association.
Why aren't you defining a one-to-many association in Customer
with cascade specified? (In the link your Service
class would replace the Order
in the example.)
Upvotes: 1