Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails delete all data from table / domain class, i.e. "deleteAll"

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".

like image 387
Ray Avatar asked Nov 16 '11 23:11

Ray


4 Answers

DomainClass.findAll().each { it.delete() }

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.

DomainClass.findAll().each { it.delete(flush:true, failOnError:true) }
like image 111
Jim Chertkov Avatar answered Oct 19 '22 17:10

Jim Chertkov


The easiest way is to use HQL directly:

DomainClass.executeUpdate('delete from DomainClass')
like image 39
ataylor Avatar answered Oct 19 '22 16:10

ataylor


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:

sessionFactory.currentSession
  .createSQLQuery("truncate table ${sessionFactory.getClassMetadata(MyDomainClass).tableName}")
  .executeUpdate()

This is only useful if your table is not referenced by other objects as a foreign key.

like image 42
Bertl Avatar answered Oct 19 '22 17:10

Bertl


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):

DomainClass.executeUpdate('delete from DomainClass')

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:

def domainObjects = DomainClass.findAll()
domainObjects.each { 
it.delete(flush:it==domainObjects.last, failOnError:true) 
}
like image 30
Saurabh J Avatar answered Oct 19 '22 17:10

Saurabh J