【问题标题】:OneToMany deleteById method in JPA repository is not workingJPA 存储库中的 OneToMany deleteById 方法不起作用
【发布时间】: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


    【解决方案1】:

    然后我想从 Section 中删除 Subsection。方法示例:

    public void deleteById(Long id) {
    subsectionRepository.deleteById(id); }

    你想做的事,不会按照你尝试的方式完成。正如你所配置的那样,它会是

    Subsenction subsenction1 = subsectionRepository.findById(id); 
    section.getSubSenctions().remove(subsenction1);
    

    然后它将从 Table Senction 中取消引用。之后由于孤立删除,它也会从表 Subsenction 中删除

    另一个非常常见的陷阱是hashCode()equals() 方法不基于 JPA 对象上的 ID 字段,或者是来自 JVM 的不基于 ID 字段的默认方法无论如何。

    【讨论】:

    • 是的,我可以在从父母中删除孩子后删除孩子
    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多