views:

487

answers:

3

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

A: 

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.)

I agree the object model would be better if the direction was inverted. Unfortunately, I am inheriting the object model from others and can not justify modifying it for backward compatibility reasons.
Andy
A: 

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.

HLGEM
This comment was not helpful. I am looking for technical solutions, not advice on how to operate in my domain.
Andy
When I see a poor design, I feel I have an obligation to point it out. I've spent too much time trying to fix trashed data from people who don't think about the effects of what they want to do.
HLGEM
A: 

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.

Andy