@ManyToMany: Howto delete associations ?
elkner Apr 22, 2005 3:28 PMDoes anybody know, how to remove a ManyToMany relationship ?
I've experimented with the follwoing case:
@Entity @Table (name="products") public class A_Product implements Serializable { private int id; A_Product() {} @Column (name ="products_id", nullable=false) @Id(generate = GeneratorType.IDENTITY) public int getId() { id } void setId(int id) { this.id = id; } @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY, mappedBy="products") public Collection<A_Category> getCategories() { return categories; } void setCategories(Collection<A_Category> categories) { this.categories = categories; } } @Entity @Table(name="categories") public class A_Category implements Serializable { private int id; @Id(generate = GeneratorType.IDENTITY) @Column(name="categories_id", nullable=false) public int getId() { return this.id; } public void setId(int id) { this.id = id; } @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER) @AssociationTable(table = @Table(name="products_to_categories"), joinColumns = { @JoinColumn(name="categories_id", referencedColumnName="categories_id") }, inverseJoinColumns = { @JoinColumn(name="products_id", referencedColumnName="products_id") }) public Collection<A_Product> getProducts() { return products; } void setProducts(Collection<A_Product> products) { this.products = products; } } @Stateless class ProductManager { @Inject private EntityManager manager; // ... @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW) public void delete(A_Product product, String clientID) { if (product == null) { return false; } manager.refresh(product); Collection<A_Category> cats = product.getCategories(); for (A_Category c : cats) { c.getProducts().remove(product); manager.merge(c); } manager.remove(product); } }
But unfortunately, this doesn't work :(. So I'tried to directly manipulate the assoc. table with
Query q = manager.createQuery("DELETE FROM products_to_categories ptc " + "WHERE ptc.products_id=:id").setParameter("id", product.getId()); q.executeUpdate();
but here I get an "unsupported" exception.
So how can one remove a relationship from the association table (cascading.all is obviously not possible)?