Wednesday, October 23, 2013

Duplicated records/data persistence/flush session error with Grails in synchronized method

Consider some of cases: 

  1. When domain fails to save data because of duplicate record.
  2. When an unsaved domain belongsTo a domain, then showing: 'save the transient instance before flushing'.
Then  - Domain.save(flush:true) - didn't work because of threading.
Here is example of my thread creation:
Thread.start {
    Domain.withTransaction {
         // Doing stuff and calling synchronization method to write data to DB
    }
}
Fix was found here: Grails, GPars and data persistence
I replaced "Domain.withTransaction" with "Domain.withNewSession":
Thread.start {
    Domain.withNewSession {
         // Doing stuff and calling synchronization method to write data to DB
    }
}
and save(flush:true) start writing into mySQL. Since data is written to mySQL, findBy... start returning proper results and therefore I application doesn't try to create duplicated record anymore. Issue solved!

No comments:

Post a Comment