【发布时间】:2021-05-13 12:09:48
【问题描述】:
我有实体并将它们存储在 h2 数据库中。省略所有不必要的字段。
@Data
@Table
@Entity
public class Section {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "section", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Subsection> subsections = new HashSet<>();
}
@Repository
public interface SectionRepository extends JpaRepository<Section, Long> {}
@Data
@Table
@Entity
public class Subsection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "SECTION_ID")
private Section section;
}
@Repository
public interface SubsectionRepository extends JpaRepository<Subsection, Long> {}
首先我保存一个Section 和一个Subsection。结果在 h2-console:
然后我想从Section 中删除Subsection。方法示例:
public void deleteById(Long id) {
subsectionRepository.deleteById(id);
}
因此没有任何内容被删除。我尝试添加orphanRemoval = true,但没有效果。
我还尝试从子级中删除父级并在没有父级的情况下再次保存Subsection,然后调用deleteById(id) 方法,结果行没有被删除,但SECTION_ID 中的值是null。还尝试了Subsection中的以下设置。
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "SECTION_ID")
private Section section;
但正如预期的那样,孩子与父母一起被删除了。 我是否错误地使用了一些注释,或者我忘了添加一些东西?孩子无法删除的原因是什么?
【问题讨论】:
标签: java jpa spring-data-jpa one-to-many