Spring Data Repository 不会删除 ManyToOne 实体
2022-09-01 02:56:13
我目前正在尝试使用Spring Data存储库来删除我的一些实体。删除调用在没有任何异常/错误消息的情况下工作,但之后不会删除实体。
这些是我的实体:
public class Board implements Serializable {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
private UUID uuid;
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval = true, mappedBy = "board")
private List<Post> posts = new ArrayList<Post>();
}
和
public class Post implements Serializable {
@Id
@GeneratedValue
private long id;
@ManyToOne(optional = false)
@JoinColumn(name="board_uuid", updatable = false, nullable = false)
@JsonBackReference
private Board board;
}
存储库非常简单:
@Repository
public interface PostRepository extends CrudRepository<Post, Long> {
}
删除调用类似于
postRepository.delete(50);
任何想法为什么这个变化没有反映在数据库中?
编辑 1:
我找到了一个解决方法,但我仍然不明白真正的问题是什么。如果我像这样删除帖子,它会“工作”(由于违反约束,有几个例外,但仍然删除了帖子):
post.setBoard(null);
postRepo.delete(post);
编辑 2:
当我查看执行的SQL语句时,我可以看到休眠甚至没有尝试删除。唯一发生的事情是这两个 select 语句:
Hibernate: select post0_.id as id1_1_0_, post0_.board_uuid as board_uu6_1_0_, post0_.content as content2_1_0_, post0_.x as x3_1_0_, post0_.y as y4_1_0_, post0_.z as z5_1_0_, board1_.uuid as uuid1_0_1_ from Post post0_ left outer join Board board1_ on post0_.board_uuid=board1_.uuid where post0_.id=?
Hibernate: select posts0_.board_uuid as board_uu6_0_0_, posts0_.id as id1_1_0_, posts0_.id as id1_1_1_, posts0_.board_uuid as board_uu6_1_1_, posts0_.content as content2_1_1_, posts0_.x as x3_1_1_, posts0_.y as y4_1_1_, posts0_.z as z5_1_1_ from Post posts0_ where posts0_.board_uuid=?
编辑 3
事实证明,帖子上的级联=CascadeType.ALL似乎是问题所在。没有它,删除工作正常(但我现在错过了对帖子的一系列更改)