user7349775
user7349775

Reputation: 21

When I delete an entry from a table which has foreign keys to others, the corresponding records are not deleted as well

I have a table (Entity) from which I delete some entries based on an ID from a different entity in Java.

This table has foreign keys to other tables, let's say the fields are ID1 and ID2. When I delete with an HQL query the entry with ID, the ones with ID1 and ID2 are still there. Those entities which have ID1 and ID2 are joined with @ManyToOne(CascadeType.ALL), so I cannot use orphanRemoval = true..

Does anyone have any idea what I should do ?

The Entity class:

@ManyToOne(targetEntity = First.class, cascade = {CascadeType.ALL})
@JoinColumn(name = "ID_LINE_HEADER")
private First lineHeader;

@ManyToOne(targetEntity = Second.class, cascade = {CascadeType.ALL})
@JoinColumn(name = "ID_LINE_CONTENT")
private Second lineContent;

The query:

        @Query(value = "" +
        "Delete " +
        "from " +
        "   Entity u " +
        "where " +
        "  u.JobExecutionId = :JobExecution ")

Upvotes: 1

Views: 1498

Answers (1)

Ilya Sereb
Ilya Sereb

Reputation: 2571

Go to the other side of the relationship (in your case First and Second class), where you have @OneToMany annotation and set the orphanRemoval attribute to true.

Just like this:

@OneToMany(mappedBy = "lineHeader", orphanRemoval = true)

Upvotes: 2

Related Questions