user10153662
user10153662

Reputation: 27

Delete Cascade doesn`t work, already tried every solution I found

Spring Rest API application. So, when I delete one User(I want to delete also the orders for that user). The user id is foreign key for the order(one to many relation).

@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<>();

The user class

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

Upvotes: 1

Views: 82

Answers (1)

Itzik Shachar
Itzik Shachar

Reputation: 754

Can you show the OrderHasProduct class as well? Here’s an working example:

@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

    }
}

Upvotes: 1

Related Questions