How to delete the object that has one-to-many association in spring jpa

163 Views Asked by At

I have a project to post, comment and like. But the problem is when i want to delete a post, comment or like object, Jpa does not delete from the database. I added the orphanRemoval = true to the one-to-many association but it still does not work. Can you help me?

This is my User Model:

@Entity
@Getter @Setter @ToString
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO,generator="native")
    @GenericGenerator(name = "native",strategy = "native")
    private Long userId;

    @Pattern(regexp = CommunicationConstants.EMAIL_REGEX_PATTERN, message = CommunicationConstants.PATTERN_DOES_NOT_MATCH_MESSAGE)
    private String email;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Pattern(regexp = SecurityConstants.PASSWORD_REGEX, message = "INVALID PASSWORD")
    private String password;

    @JsonIgnore
    @OneToMany (mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Authority> authorities;

    @OneToMany (mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments;

    @OneToMany (mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Post> posts;

    @OneToMany (mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Likes> likes;
}

And this my Post Model:

@Entity
@Getter @Setter
public class Post {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO,generator="native")
    @GenericGenerator(name = "native",strategy = "native")
    private Long postId;

    @OneToMany (mappedBy = "post", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments;

    @OneToMany (mappedBy = "post", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Likes> likes;

    @ManyToOne(fetch = FetchType.LAZY)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    @JoinColumn (name = "user_id")
    private User user;
}

Comment and Like models are similar to post model.

And this is my Post Service. But when i run deletePost() it does not delete. And throws no exception

@Service
@AllArgsConstructor
public class PostService {

    private final PostRepository postRepository;

    public Result createNewPost (Post post) {

        try {
            post.setComments(new ArrayList<>());
            post.setCreatedAt(new Date());
            return new DataResult<>(true, NEW_POST_CREATED, postRepository.save(post));
        }
        catch (Exception e) {
            return new Result(false, e.getMessage());
        }
    }

    public Result deletePost(Post post, User user) {

        if (post == null) {
            return new Result(false, POST_NOT_FOUND);
        }
        else if (post.getUser().equals(user)) {
            try {
                postRepository.delete(post);
                return new Result(true, POST_DELETED);
            }
            catch (Exception e) {
                e.printStackTrace();
                return new Result(false, e.getMessage());
            }
        }
        else {
            return new Result(false, PERMISSION_DENIED);
        }
    }
}
1

There are 1 best solutions below

1
Mar-Z On

The problem here is the usage of the method equals() of the entity User. As it is not implemented the default implementation of the Object class will be invoked. This is not correct for your use case and will be always false.

Instead of

if (post.getUser().equals(user))

Use something like

if (post.getUser().getUserId().equals(user.getUserId()))