Я работаю с приложением Spring Boot, используя JPA/Hibernate, и столкнулся с проблемой, из-за которой объекты PostComment не удаляются при удалении объекта Post, несмотря на использование каскадирования и удаления сирот в моих сопоставлениях.
Моя настройка сущности аналогична примеру Влада Михалчи по сопоставлению ассоциаций OneToMany и ManyToOne, я только что добавил родительскую сущность как Пользователь.
Код: Выделить всё
@Entity(name = "User")
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List
posts = new ArrayList();
// Synchronization method for posts
public void addPost(Post post) {
posts.add(post);
post.setUser(this);
}
public void removePost(Post post) {
posts.remove(post);
post.setUser(null);
}
}
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
private List comments = new ArrayList();
// Synchronization method for user
public void setUser(User user) {
this.user = user;
}
// Synchronization methods for comments
public void addComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}
public void removeComment(PostComment comment) {
comments.remove(comment);
comment.setPost(null);
}
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
}
Код: Выделить всё
public void removePostFromUser(Long userId, Long postId) {
User user = userService.findUserById(userId);
Post post = this.findByPostIdAndUser(postId, user);
user.removePost(post);
userService.saveUser(user);
}
Код: Выделить всё
public void removePostFromUser(Long postId){
Post post = findById(postId);
User user = post.getUser();
userService.saveUser(user);
}
- When testing this service, both Post[/b] and it's associated PostComment entity is deleted. However when debugging, the Post entity is successfully removed, but its associated PostComment entities remain in the database. What could be the reason PostComment entities are not being deleted as expected?
- Between these two methods, which is considered a better practice for
deleting entities in such a relationship? Or is there a more
effective approach?
Источник: https://stackoverflow.com/questions/781 ... is-removed
Мобильная версия