简体   繁体   中英

Hibernate won't remove parent but removes children (or relationship) when it fails to delete parent because of foreign key constraint

I have some entities (WarehouseTransactionGroup, WarehouseTransactionAttribute, AttributeValue) with following relationship:

@Entity
public class WarehouseTransactionGroup extends MasterEntity {

   @ManyToMany(cascade = CascadeType.ALL)
   @MapKeyColumn
   private Map<WarehouseTransactionAttribute, AttributeValue> attributes;

   // Getter and setter

}

When I try to remove a object of type WarehouseTransactionGroup, it naturally fails due to foreign key constraint since the object is used in some other database record. However, Hibernate clears the data in attributes field.

I am calling remove operation, ie, session.delete() inside a transaction.

Why is this happening and how can I fix it?

You shouldn't use CascadeType.ALL for @ManyToMany associations.

  1. You need to change the cascade to CascadeType.PERSIST, CascadeType.MERGE :

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @MapKeyColumn private Map attributes;

  2. The delete goes like this:

     WarehouseTransactionGroup wtg = ...; attributes.clear(); em.remove(wtg); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM