Search code examples
javahibernatejpapersist

How to remove entity and children


I have one problem to solve. I have two entities: Action and Logging:

@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;

Only Logging table has a column action_id as a FOREIGN KEY.

One action can have multiple Logging records.

The question is: how can I delete all Action entities that have a date before a certain date and have a certain domain (which lies in a Logging table)? For example

deleteActionByDateAndDomain(LocalDateTime date, String domain)

Logging entity is the owner, right? So, Should I delete Action entity and then all related Logging entities by for example CASCADING? Or conversely - firstly remove all Logging entities which fulfill my conditions (date before dateX and domain == myDomain passed as parameters)?

How would you implement it? I could, for example, delete Action entity and all related Logging entities but there is no field domain in Action entity (only in Logging).

If possible, I should use CrudRepository interface.

Thank you very much in advance!


Solution

  • You can specify the cascade type to cascade the delete operation by setting the attribute cascade = CascadeType.REMOVE but this may cause you some headaches if not used correctly:

    • If you delete some record by mistake, potentially a lot of data can be deleted in cascade
    • The application can become slow because of many queries executed by Hibernate (link)

    So, if you don't want these issues, you can manage the deletions manually. When you delete some record you will know what else needs to be deleted as a consequence. The advantage is that you have more control and you can optimize the process by creating bulk deletions if needed.