Showing posts with label withNewSession. Show all posts
Showing posts with label withNewSession. Show all posts

Wednesday, December 18, 2013

Grails withNewSession


Please follow the following scenario:
1. You are saving a domain object 'User'.
2. You are trying to save another domain object 'Activities', indicates that 
   who is saving 'User'.
3. First, 'User' created, so now time to save 'Activities'.
4. But activities failed, what would be the saved user? 'User' would be roll 
   back even if 'Activities' saving between try catch, because of hibernate 
   session?
5. In this scenario you must save your 'Activities' under try catch with 
   'new session', such:

def saveUser = [
    User user = new User(name: "Pritom").save();
    try {
        Activites.withNewSession { sesstion -> 
            new Activities(createdBy: "some name").save();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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!