java – JPA: Many-to-many records are not deleted

Question:

I have a problem with database design

There is a User entity

public class User implements UserDetails, Serializable {

    // ...

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

    // ...

}

It refers to the entity Manager

public class Manager {

    // ...

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

    @OneToOne(mappedBy = "manager", orphanRemoval = true, cascade = CascadeType.ALL)
    private User user;


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


    // ...

}

There is a ParticipantRequest entity. References many to one to the entity Manager

public class ParticipantRequest {

    // ...

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

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

    // ...

}

And there is a link table between Manager and 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;

    // ...

}

I expect that by deleting User , I will have the Manager and its associated ExpertAndRequest deleted . But instead, nothing happens … No error, nothing happens. As if everything worked out correctly

I delete like this:

@GetMapping("/some/url")
@Transactional
@ResponseBody
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.userRepository.delete(manager.getUser());

    return res;
}

What am I doing wrong? I have been fighting for the 3rd day and all without success (

Answer:

I'm not at all sure if this is the answer to this question, but there is such an annotation as

@OnDelete(action = OnDeleteAction.CASCADE)
Scroll to Top
AllEscort