petar.tahchiev (11) [Avatar] Offline

I'm working on a JPA-enabled project, which is designed to be modular. The core of the project contains some @Entity-ies and the modules add more @Entity-ies, depending on which jar you include in the classpath. My problem occurs when I try to include the promotion module. The promotion module contains the ProductPromotion entity, which has a Set of Product-s, and they are mapped with @ManyToMany:

public class ProductPromotion {

@ManyToMany(fetch = FetchType.LAZY, targetEntity = Product.class, cascade = { CascadeType.ALL })
@JoinTable(name = "productpromotion_product", joinColumns = @JoinColumn(name = "promotion_pk"), inverseJoinColumns = @JoinColumn(name = "product_pk"))
private Collection<Product> products;

I only map ProductPromotion, because Product is in the core, and it doesn't know if the promotion module will be enabled, so ProductPromotion is not in its classpath. This way the ProductPromotion becomes the owning side of the @ManyToMany, and when I try to delete a Product from the db it fails with constraint violation exception that productpromotion_product table has a foreign key pointing to this product so it cannot be deleted. I was hoping that the @ManyToMany annotation has the orphanRemoval attribute but it seems like it is not there smilie .. Can you please tell me why is it not there? What I would like to do is when deleting the product to have the records from productpromotion_product associated with that product automatically deleted. Or at least make hibernate not throw the exception. Is that possible?
382995 (1) [Avatar] Offline
Agree with question.

It's common practice to create unidirectional ManyToMany associations in applications (for example: tag system, categories system, ... etc ). And it is always a headache for me to find most elegant way to delete child element and all references to it.

I've used two methods to delete unidirectional ManyToMany child element:

- Native sql: delete all references to the child element from join table ("productpromotion_product" table from previous post example), then delete element row from child entity table (table that stores "Product" entity from previous post example);

- Remove via persistence context: retrieve all parent entities ("ProductPromotion" from previous post example), remove element from all parent entities collections ("Collection<Product> products" from previous post example), then delete child element.

I don't like both methods.

What method of deletion unidirectional ManyToMany child entity is recommended by Hibernate developer team / "Java persistence with Hibernate" authors?

There are a lot of same topics on Stackoverflow and Hibernate forum, but either they half-answered, or unanswered at all.

Thank you.