Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA and remove entries from @ManyToMany

As touched on in the following:

  • Cascade on delete using unidirectional Many-To-Many mapping
  • How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?
  • JPA JPQL: select items when attribute of item (list/set) contains another item

when removing entries from @ManyToMany mappings, there is an element of manual tweaking involved to remove the foreign keys.

I have been using my own JPA CRUD for years and have a nice solution for this: CrudDao e.g. NoteDao.

But I've been recently very impressed by Spring JPA and the ability to autogenerate Cruds by declaring an interface and then creating similarly named namedQuerys on the @Entity.

But how do I fix the @ManyToMany remove problem? I'll essentially have remove methods on my Crud that expose this "feature" of JPA.

like image 987
fommil Avatar asked Apr 05 '13 17:04

fommil


1 Answers

I appear to have solved this using @PreRemove, as noted in https://stackoverflow.com/a/14911910/1041691

e.g. https://github.com/fommil/zibaldone/blob/master/src/main/java/com/github/fommil/zibaldone/Note.java#L74

like image 83
fommil Avatar answered Nov 04 '22 00:11

fommil