简体   繁体   中英

Java: Hibernate - Query to delete from multiple tables

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

In entity AI 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.

您可以使用本机查询,以下应该在mysql中工作:

delete a , b from a inner join b on a.id=b.a_id where ...

您可以使用delete cascade上的参数设置外键,这样当它引用的键被删除时,它所作为外键的所有行也将被删除。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM