我打电话有问题 deleteById
在@datajpatest中。从类似的问题中尝试了许多解决方案,但都无济于事。以下是实体:
实体:
@Setter
@Getter
@NoArgsConstructor
@Entity
@DynamicUpdate
@Table(name = "project")
public class Project{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private String description;
@Column
@CreationTimestamp
private LocalDateTime created;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Project parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Project> subProjects = new HashSet<>();
}
J储蓄
@Repository
public interface ProjectRepository extends JpaRepository<Project, Long>{
}
测试
@Test
void givenParentAndChilds_whenDeleteParent_thenDeleteChilds() {
// Given
Project parent = Project.builder().name("parent").build();
parent = projectRepository.save(parent);
Project child1 = Project.builder().name("child1").build();
child1.setParent(parent);
child1 = projectRepository.save(child1);
Project child2 = Project.builder().name("child2").build();
child2.setParent(parent);
child2 = projectRepository.save(child2);
Project child3 = Project.builder().name("child3").build();
child3.setParent(parent);
child3 = projectRepository.save(child3);
assertTrue(projectRepository.findById(parent.getId()).isPresent());
assertTrue(projectRepository.findById(child1.getId()).isPresent());
assertTrue(projectRepository.findById(child2.getId()).isPresent());
assertTrue(projectRepository.findById(child3.getId()).isPresent());
// When
projectRepository.deleteById(parent.getId());
// Then
assertFalse(projectRepository.findById(parent.getId()).isPresent());
assertFalse(projectRepository.findById(child1.getId()).isPresent()); // <-- these assertions fails
assertFalse(projectRepository.findById(child2.getId()).isPresent());
assertFalse(projectRepository.findById(child3.getId()).isPresent());
}
在测试期间,子项不会通过级联删除。我试过以下方法:
添加 orphanRemoval = true
至 @OneToMany
中的注解 Project
实体
添加 deleteById
与 @Transactional
在 ProjectRepository
添加 @Transactional
作为测试注解
以上都不起作用,childs不能删除。在spring引导日志中 DELETE
查询也丢失。我的考试怎么了?
1条答案
按热度按时间acruukt91#
解决方法是在两个方向之间正确设置双向链接
parent
以及childs
: