In one of the modules that I was working on , I needed to delete the previous data from a table then load up the data into those tables again and then manipulate code through the ‘id’s’ on those tables.
So this is what I was doing …
Event.executeUpdate(‘delete from Event’)
EventInstance.executeUpdate(‘delete from EventInstance’)
But the problem was that when I deleted the events, the ‘id’s’ on those tables would remain intact and the new Events that would load up would continue upon the earlier present ‘ id’s ‘ .i.e if the last present id was 24 before deleting , the new load-ups would continue from 25 onwards..
This made realise that truncate was a better option … But unfortunately the GORM layer does not support the ‘ truncate ‘ queries that I was looking for.
So in effect this query would give an error
Event.executeUpdate(‘truncate table Event’)
EventInstance.executeUpdate(‘truncate table EventInstance’)
So with some help from ‘ Mr. Google ‘ and my fellow colleagues , i realised that there was another way to do this ..
Session Factory …
Session Factory allowed me to truncate those tables through createSQLQuery() method
So my new approach was
def session = sessionFactory.getCurrentSession()
Query query = session.createSQLQuery(‘truncate table event’)
The getCurrentSession() method looks at the current context to see if a session is stored in there. If there is one, it uses it, and if there isn’t a session in the current context, it creates a new one and saves it in there.
Then all I did was use the query to truncate the tables… and presto !! .. my work was done ..
Hope this helps .. 😀
Manoj (at) Intelligrape (dot) com