I have three entities, Bag
, Item
and Category
. One Bag
can have Many Items
and Many Items
can have Many Categories
:
Bag
<----OneToMany
----> Item
Item
-----ManyToMany
-----> Category
It isn't necessary store items
in Category
When I try delete a Item
without categories
, there isn't any error message, but the Item
isn't deleted. However if i try delete the same item
in DataBase, it is deleted successfully.
On the other hand, if i try delete a Item
with categories
, i receive this error message:
"Cannot delete or update a parent row: a foreign key constraint fails (item_categories
, CONSTRAINT fk_item_categories_items_id
FOREIGN KEY (items_id
) REFERENCES item
(id
))".
I would like delete the item
and the relation with his categories
, but keep categories
. How could I do this?
For the first problem, I have tried add to the delete method bag.removeItems(item)
, but it only deletes tthe relationship between both and the item
continues in DB.
Bag.java
@OneToMany(mappedBy = "bag", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JsonIgnoreProperties("bag")
private Set<Item> items = new HashSet<>();
Item.java
@ManyToOne
@JsonIgnoreProperties("items")
private Bag bag;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "item_categories",
joinColumns = @JoinColumn(name="items_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="categories_id", referencedColumnName="id"))
private Set<Category> categories = new HashSet<>();
ItemResource.java
@DeleteMapping("/items/{id}")
@Timed
public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
itemRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
EDIT: The methods of create and update works fine.