如何删除实体和 children

How to remove entity and children

我有一个问题要解决。我有两个实体:ActionLogging:

@Entity
public class Action {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    ...other fields
    ...other fields


    @Column
    private Date start;

    @Column
    private Date end;


@Entity
public class Logging {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @ManyToOne
    @JoinColumn(name = "action_id")
    private Action action;

    ..not important fields

    @Column
    private String domain;

    @Column
    private Date date;

只有日志记录 table 有列 action_id 作为 FOREIGN KEY

一个动作可以有多个Logging记录。

问题是:如何删除日期早于特定日期且具有特定域(位于日志记录 table 中)的所有操作实体? 例如

deleteActionByDateAndDomain(LocalDateTime date, String domain)

记录实体是所有者,对吧?那么,我是否应该通过例如 CASCADING 删除 Action 实体,然后删除所有相关的 Logging 实体?或者相反 - 首先删除满足我条件的所有日志记录实体(date before dateX and domain == myDomain 作为参数传递)?

你会如何实施? 例如,我可以删除 Action 实体和所有相关的 Logging 实体,但 Action 实体中没有字段域(仅在 Logging 中)。

如果可能,我应该使用 CrudRepository 接口。

非常感谢您!

您可以通过设置属性cascade = CascadeType.REMOVE指定级联类型来级联删除操作,但是如果使用不当可能会让您头疼:

  • 如果误删某条记录,可能会级联删除大量数据
  • 由于 Hibernate (link) 执行的许多查询,应用程序可能会变慢

因此,如果您不希望出现这些问题,可以手动管理删除。当你删除一些记录时,你会知道还有什么需要删除。优点是您拥有更多控制权,并且可以根据需要通过创建批量删除来优化流程。