3

I have two tables connected by a foreign key with a one to many relation.

In entity A I have the following:

@org.hibernate.annotations.Cascade( {
    org.hibernate.annotations.CascadeType.ALL,
    org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@OneToMany(mappedBy="monitoredFlight", fetch = FetchType.LAZY)
@OnDelete(action=OnDeleteAction.CASCADE)
private List<bTable> BTable = new ArrayList<BTable>();

Now I try to delete from table A with a bulk delete query:

Query query = em.createQuery("delete from A where originDateTime<:date");

and I get the foreign key constraint error. I decided to do the delete with a join just as I would in mysql, so I changed it to:

Query query = em.createQuery("delete from A join BTable where originDateTime<:date");

and I got a syntax error. I have tried several combination with or without join and nothing works; any ideas?

I am using mysql for the database and java for the language.

0

2 Answers 2

4

You can use a native query, the following should work in mysql:

delete a , b from a inner join b on a.id=b.a_id where ...
Sign up to request clarification or add additional context in comments.

Comments

1

You can setup a foreign key with the parameter on delete cascade so that when the key it references is deleted all rows that it is a foreign key on are also deleted.

2 Comments

i have that allerady but i want to do a massive deletion and not a one by one deletion.
What do you mean? Every row that is deleted in Table A will subsequently cause a cascade delete on Table B for any rows that share the foreign key - hence you won't get the constraint error, instead all the foreign key mapped rows in Table B will also be deleted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.