grails 从表/域类中删除所有数据,即“deleteAll”
我有一个域类 Widget,我需要删除其中的所有实例 - 将其清除。之后,我将加载新数据。您建议采取什么机制来做到这一点?
PS 请注意,这不是在引导时,而是在“运行时”。
I've got a domain class, Widget, that I need to delete all instances out of -- clear it out. After that, I will load in fresh data. What do you suggest as a mechanism to do this?
P.S. Note this is not at bootstrap time, but at "run-time".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的方法是直接使用HQL:
The easiest way is to use HQL directly:
如果您想避免任何 GORM 陷阱,例如需要立即删除对象并检查以确保它确实被删除,请添加一些参数。
If you want to avoid any GORM gotchas, such as needing to delete the object immediately and checking to make sure it actually gets deleted, add some arguments.
相当旧的帖子,但仍然真实。
如果您的表非常大(数百万个条目),那么使用 findall()*.delete() 进行迭代可能不是最佳选择,因为除了 GreenGiant 指出的潜在内存问题之外,您还可能遇到事务超时(例如 MySQL innodb_lock_wait_timeout 设置)。
因此,至少对于 MySQL Innodb,使用 TRUNCATE TABLE 更快:
只有当您的表没有被其他对象作为外键引用时,这才有用。
Fairly old post, but still actual.
If your table is very large (millions of entries), iterating using findall()*.delete() might not be the best option, as you can run into transaction timeouts (e.g. MySQL innodb_lock_wait_timeout setting) besides potential memory problems stated by GreenGiant.
So at least for MySQL Innodb, much faster is to use TRUNCATE TABLE:
This is only useful if your table is not referenced by other objects as a foreign key.
根据我的了解,我同意@ataylor,如果您的域对象中没有关联,下面的代码是最快的(在任何实际应用程序中极不可能):
但是如果您与其他域有关联,那么最安全的删除方法(和也比上面提到的慢一点)如下:
From what I learnt, I agree with @ataylor the below code is fastest IF there are no associations in your domain object (Highly unlikely in any real application):
But if you have assiciations with other domains, then the safest way to delete (and also a bit slower than the one mentioned above) would be the following:
如果您有一个对象列表并想要删除所有元素,可以使用
*
运算符。例子。
If you have a list of objects and want to delete all elements, you can use
*
operator.Example.