Reputation: 337
I have a @OneToMany
bi-directional relationship with @ManyToOne
children. The children are on the owning side.
I want to delete children individually upon user command via the parent and if the last child is removed, then delete the parent.
Parent.java
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Child> children;
...
Child.java
@ManyToOne(fetch = FetchType.EAGER)
private Parent parent;
...
void remove(Parent parent, Child child) {
for(Child c : parent.getChildren()){
if(c.equals(child)){
parent.getChildren().remove(c);
break;
}
}
if(parent.getChildren().isEmpty()){
parentService.remove(parent); // *1
} else {
parentService.update(parent); // *2
}
}
The updates at marker *2
work fine. But when the last record is found and the code at line marked with *1
executes I get this exception :
org.springframework.dao.InvalidDataAccessApiUsageException: Removing a detached instance com.package.etc.Parent#18374850;
nested exception is java.lang.IllegalArgumentException: Removing a detached instance com.package.etc.Parent#18374850 at
org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:301)
I've tried calling update before the remove, but get the same exception.
Any ideas?
Upvotes: 2
Views: 2042
Reputation: 337
I managed to resolve it. I hadn't annotated the method @Transactional.
Upvotes: 1