Search code examples
postgresqlhibernatejpasql-deletecascade

JPA: How to remove user and all references from other tables?


When I am deleting a user from the users table, all of his posts and any comments to this posts should be deleted as well.

The model looks like the following:

@Data
@Entity @Table(name = "users")
public class BlogUser {

    @Id
    private String userName;
    private String password;
    private String email;

    @Enumerated(EnumType.STRING)
    private Role role;

    private boolean enabled;
}

post instance has a reference to belonging user:

@Data
@Entity @Table(name = "posts")
public class Post {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String postText;

    @ManyToOne(cascade = CascadeType.ALL)
    private BlogUser user;

    private LocalDateTime createdDate;
}

The same situation applies for comments.

Now when I want to perform a delete I get this error:

org.postgresql.util.PSQLException: ERROR: update or delete on table "users" violates foreign key constraint "fkqdk379brhxkbj4c8qenbuu85l" on table "posts"

DB is Postgres. I tried to use @ManyToOne(cascade = CascadeType.ALL), but it didn't help.

UPDATE:

The idea is that I want to keep current schema for tables.
Without adding posts and/or comments to BlogUser class.


Solution

  • You need to add cascade to BlogUser side also in order to have delete on it to be cascaded to Post & Comment.

    Add something like this to your BlogUser class:

    @Getter
    @OneToMany(cascade=CascadeType.ALL, mappedBy="user")
    private Collection<Post> posts = new HashSet<>();
    
    @Getter
    @OneToMany(cascade=CascadeType.ALL, mappedBy="user")
    private Collection<Comment> comments = new HashSet<>();