JPA OneToMany - 删除最后一个Child时删除Parent

时间:2013-01-04 12:55:02

标签: java hibernate jpa

我与@OneToMany个孩子有@ManyToOne双向关系。孩子们都在自己的身边。

我希望通过父项单独删除子项,如果删除了最后一个子项,则删除父项。

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
    }
}

标记*2的更新正常。但是当找到最后一条记录并且标有*1的行的代码执行时,我得到了这个例外:

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)

我尝试在删除之前调用更新,但获得相同的异常。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。我没有注释@Transactional方法。

相关问题