Hi
I've been fighting with how to delete child objects in a OneToMany all day. At first I didnt realise that JPA does not (yet) support delete-orphan, so although the link between my parent and child(ren) was being severed, the child was still in the Database.
Then I ran into all sorts of concurrent modification issues because I was using my collection in a for(Child c: children).... loop, and of course, calling children.remove(c) in this case will cause that problem.
So, based on the other posts I've read, I think I have the solution, which is shown below in case it's helpful to other people who are beginners like me
Code:
FileType fileType = findFileType(fileTypeId);
Iterator it = fileType.getFields().iterator();
while(it.hasNext()) {
Field f = (Field)it.next();
if(fieldIds.contains(f.getFieldId())) {
it.remove();
entityManager.remove(f); // this bit required because JPA doesnt support delete-orphan
}
}
Here's my mapping btw - it uses the default cascade behaviour (ALL) and uses a join table
Code:
@OneToMany(fetch=FetchType.LAZY)
@JoinTable(
name="FILE_TYPE_FIELD",
joinColumns = @JoinColumn(name="FILE_TYPE_ID", referencedColumnName="FILE_TYPE_ID"),
inverseJoinColumns = @JoinColumn(name="FILE_FIELD_ID", referencedColumnName="FILE_FIELD_ID")
)
What I would really appreciate is if someone could just say yeah (or no), this is the standard way of doing things, because I struggled a bit finding good examples, and I am going to be writing a whole load of these soon so I want to do them right :)
Also, for bonus points, the docs recommend using a join table, even though a simple foreign key would suffice. Why is this?
Thanks