1

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 ")
  • 1
    The behavior you describe is what one normally wants. Cascading deletes make sense from the "one" side to the "many" side, but rarely from the "many" side to the "one" side. – John Bollinger Jun 12 '19 at 14:56
  • Possible duplicate of [How to Delete using INNER JOIN with SQL Server?](https://stackoverflow.com/questions/16481379/how-to-delete-using-inner-join-with-sql-server) – LoaStaub Jun 12 '19 at 15:11
  • Nope, it is not related – user7349775 Jun 12 '19 at 15:19
  • Possible duplicate of [JPA delete all entites works strange](https://stackoverflow.com/questions/37696829/jpa-delete-all-entites-works-strange) – Alan Hay Jun 13 '19 at 08:39
  • Bulk delete via JPQL does not trigger a cascade. See question and answer referenced above. Cascading deletes will only be triggered via `entityManager.remove(e)` – Alan Hay Jun 13 '19 at 08:39
  • Isn't the answer from Ilya what worked for you? if yes then please accept (and in general upvote if it is a useful answer). – Simon Sobisch Jun 20 '19 at 18:46

1 Answers1

2

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)
Alan Sereb
  • 2,358
  • 2
  • 17
  • 31