JPA:相关记录不会被删除

时间:2018-05-11 17:31:20

标签: java jpa

我遇到数据库设计问题

有一个实体用户

public class User implements UserDetails, Serializable {

    // ...

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "MANAGER_ID")
    private Manager manager;

    // ...

}

用户实体相关联的经理实体

public class Manager {

    // ...

    @OneToMany(mappedBy = "manager", orphanRemoval = true)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<ExpertAndRequest> requests;

    @OneToOne(mappedBy = "manager", orphanRemoval = true)
    private User user;


    @OneToMany(mappedBy = "manager")
    private List<ParticipantRequest> participantRequests;


    // ...

}

ExpertAndRequest实体是经理 ParticipantRequest 实体之间的多对多链接表

public class ExpertAndRequest implements Serializable {

    // ...

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "managerId", updatable = false, insertable = false, referencedColumnName = "id")
    private Manager manager;


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "requestId", updatable = false, insertable = false, referencedColumnName = "id")
    private ParticipantRequest request;

    // ...

}


public class ParticipantRequest {

    // ...

    @OneToMany(mappedBy = "request", cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<ExpertAndRequest> experts;

    @ManyToOne
    @JoinColumn(name = "manager_id")
    private Manager manager;

    // ...

}

删除经理时

this.managerRepository.delete(manager);
this.managerRepository.flush();

我希望使用正确的经理和相关的用户删除 ExpertAndRequest 行。但这不会发生并出现错误

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : my.package.name.model.Manager.user -> my.package.name.model.User

我做错了什么?谢谢!

更新这是我删除之前的全部内容。除了删除

public ManagerApiResult deleteManager(@RequestParam(name = "id") Long id) {
    if(!this.isUserManager()) {
        return null;
    }

    ManagerApiResult res = new ManagerApiResult();

    Manager manager = this.managerRepository.findOne(id);

    if(manager == null) {
        res.errors.add(String.format("Manager id \"%s\" do not exist", id));
        return res;
    }
    this.managerRepository.delete(manager);
    this.managerRepository.flush();
    return res;
}

1 个答案:

答案 0 :(得分:0)

例外是自我解释

在您的实体图表(管理员用户)的某个位置,您有一个User的实例,在删除persisted之前尚未manager