删除Cascade不起作用,已经尝试了我发现的每个解决方案

时间:2018-12-07 19:08:21

标签: java spring rest cascade

Spring Rest API应用程序。因此,当我删除一个用户时(我也想删除该用户的订单)。用户ID是订单的外键(一对多关系)。

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id")
public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

@OneToMany(
        mappedBy = "order_products", 
        cascade = CascadeType.ALL, 
        orphanRemoval = true
    )
private List<OrderHasProduct> orders = new ArrayList<>();

用户类别

@OneToMany(
    mappedBy = "orders", 
    cascade = CascadeType.ALL, 
    orphanRemoval = true
)
private List<OrderHasProduct> orders = new ArrayList<>();

public boolean deleteUser(int id){
    User usr = usrRepository.findById(id);
    if (usr == null) {
        throw new ResourceNotFoundException(User.class.getSimpleName());
    }

    usrRepository.delete(id);
    User deletedUser = usrRepository.findById(id);
    if (deletedUser != null) 
       return false;

    return true;
} 

1 个答案:

答案 0 :(得分:1)

您还可以显示OrderHasProduct类吗? 这是一个有效的示例:

@Entity
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post", 
        cascade = CascadeType.ALL, 
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    //Constructors, getters and setters
}

@Entity
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

    //Constructors, getters and setters

    }
}