2

I want to delete entries from an embedded map. If the object CategoryTag is deleted, I want to execute a HQL query in an interceptor, which deletes the entries from a map:

'Product' model:

@NotNull
@ElementCollection
@CollectionTable(name = "producttag", joinColumns=@JoinColumn(name="id"))
protected Map<CategoryTag, String> tags = new HashMap<CategoryTag, String>();

I am kinda blank how i can write the HQL query. It starts with the problem, that I do not know how to reference the map in a delete query. delete Product.tags t where t.key = :tag fails with an Product.tags is not mapped exception.

Can somebody help me on this?

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
Flo
  • 1,469
  • 1
  • 18
  • 27

1 Answers1

1

Tags is not entity.

A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

This is why you are getting the error. The correct way is to load Entity, update its collection and then save this object.

Product p = session.load(Product.class, id);
p.removeTags(tag);
session.flush();
danny.lesnik
  • 18,479
  • 29
  • 135
  • 200
  • `CategoryTag` does not have a reference to `Product`, so it basically does not know, which products are using it. So in order to do it the way you suggested, I would have to select all products which contain the tag and then delete it in a loop, as you suggested. However, I wonder if there is a way to do it with one simple statement. I can do it with a native query: `delete from producttag where tags_KEY = :tag` but this causes caching problems, so I was wondering if there was a way to do it in HQL. – Flo Feb 16 '13 at 12:29
  • I believe you still need to do the way I told you and this way will help you to skip caching problems. – danny.lesnik Feb 16 '13 at 17:45