0

How to write code with many-to-many relationship without using jpa @manytomany annotation? For example for two classes Software and for Tags. When i delete Tag - it removes all software. I tried to do it with @manytomany annotation using various approaches but it does not work. I have seen something similar to my question in this site but any gives the code sample. (I guess it should be @OneToMany relationships in both sides, but it would be great to take a code).

Or how to do it with using @manytomany if it possible.

More info: if we have soft1, soft2 <--> tag1, and soft2 <--> tag2, and we delete tag1, then only soft1 should be deleted. Does hibernate can handle it?

ses
  • 13,174
  • 31
  • 123
  • 226
  • Do you mean that you want to do a cascade-delete on a many-to-many relationship? – Augusto Mar 17 '11 at 12:36
  • maybe it's somehow related to DELETE_ORPHAN – ses Mar 17 '11 at 12:49
  • @user369759 - http://stackoverflow.com/questions/306144/jpa-cascadetype-all-does-not-delete-orphans – Satadru Biswas Mar 17 '11 at 13:31
  • Hi ! I also have the same requirement. I have a @ManyToMany relationship. Now what I need is, if I delete tag2, then only tag2 and any assoiciation in tag_soft table should be deleted and soft2 should not be deleted. and if i delete soft2 then soft2 and any association in tag_soft table should be deleted but tag1 and tag2 should no be deleted. Could you help me in this ? – Vasu Apr 01 '11 at 05:35
  • you should find and delete assassinations by hand to resolve constrains - delete in your objects and then save() changes and only after this delete your object. all this you may want to do in the context of one transaction. – ses May 02 '11 at 13:05

1 Answers1

0

try with

@org.hibernate.annotations.Cascade(
   {org.hibernate.annotations.CascadeType.PERSIST, 
    org.hibernate.annotations.CascadeType.MERGE, 
    org.hibernate.annotations.CascadeType.REFRESH, 
    org.hibernate.annotations.CascadeType.DETACH, 
    org.hibernate.annotations.CascadeType.DELETE_ORPHAN}
)

This is to remove org.hibernate.annotations.CascadeType.REMOVE from the cascade to avoid the following scenario

  • You delete Software with id:5
  • hibernate deletes Tags with id:5 and 7
  • ALL the rows of software tagged with those ids are deleted, and the cascade starts again, so you might end up with an empty DB.
Augusto
  • 28,839
  • 5
  • 58
  • 88