我对 cascade="delete" 的工作原理有点困惑(...)
级联delete
操作意味着如果您delete
是父级,则操作将沿关联传播。所以在你的情况下,删除一个City
实体应该传播到Client
s.
因此,当我运行 (...) 时,是否也应该删除所有客户端
The Session#delete(String)
method that takes a HQL query string, executes it, iterates over the results and calls Session#delete(Object)
on each object respect cascading (so the Clients will be deleted if your query is really a HQL query).
But this method is old and has been deprecated in Hibernate 3 (and moved to the "classic" Session
interface), I do not really recommend it (it performs 1+N operations and is pretty inefficient to delete a huge number of results).
If this is a concern, prefer the bulk delete support offered by Hibernate:
int deleteCount = session.createQuery("delete from Foo where bar = :bar")
.setParameter("bar", bar);
.executeUpdate()
But note that bulk delete has restrictions:
- You can not use aliases.
- No inner joins in the query (although you can use subselects in the where clause).
- A bulk delete does not cascade (and won't take care of join tables).
So with a bulk delete, you'd have to delete the Client
before the City
. But performances are much better.
PS: You need to commit()
at some point (and also improve your error handling i.e. rollback()
in the catch block)
References
- Hibernate Core Reference Guide