2

I have 2 entites:

@Entity
@Table(name="product")
public class Product {
    private Long id;
    private Set<Upgrade> upgrade;

    @Id
    @Column(name="id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany(mappedBy = "products",
                targetEntity = Upgrade.class,
                cascade = CascadeType.REFRESH,
                fetch = FetchType.EAGER)
    public Set<Upgrade> getUpgrade() {
        return upgrade;
    }

    public void setUpgrade(Set<Upgrade> upgrade) {
        this.upgrade = upgrade;
    }
}

and

@Entity
@Table(name="upgrade")
public class Upgrade {
    private Long id;
    private Set<Product> products;

    @Id
    @Column(name="id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToMany(targetEntity = Product.class, cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
    @JoinTable(name = "upgrade_product",
               joinColumns = @JoinColumn(name = "upgrade_id"),
               inverseJoinColumns = @JoinColumn(name="product_id"))
    public Set<Product> getProducts() {
        return products;
    }

    public void setProducts(Set<Product> products) {
        this.products = products;
    }
}

My data creates these so that a product contains a set of multiple upgrades.

i.e. P1 {U1, U2, U3, U4} P2 {U1, U3, U5, U7}

If I delete an upgrade, then everything is fine. It is just removed from the product. However, if I delete a product then it attempts to delete all of the linked upgrades.

How do I get this to be able to delete the product and leave the upgrades in place.

1 Answer 1

3

Before you delete the Product, clear its Set<Upgrade> and save the Product. Something like:

public void delete(Product p)
{
    p.setUpgrade(Collections.emptySet());
    entityManager.remove(entityManager.merge(p));
}
Sign up to request clarification or add additional context in comments.

5 Comments

merge is only necessary if the product is not already in the persistence context.
That doesn't explain why it's needed and why it isn't when deleting an upgrade.
@JB because the Product is the parent side of the relationship, so Hibernate sees products as owning updates.
@Matt: There is no cascade delete on the association, so Hibernate shouldn't delete the upgrades, unless I miss something.
@JB oh, I completely missed that the OP had actually specified CascadeType.REFRESH. Hmm...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.