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.
You need to change the cascade to CascadeType.PERSIST, CascadeType.MERGE
:
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @MapKeyColumn private Map attributes;
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.