2

I'm writing a Grails application and I need to retrieve a persistent value for the collection of my domain class objects. Let's consider we have got the following domain object:

class UserGroup {
   SortedSet<User> users
   static hasMany = [ users: User ]
   // ...
   def beforeUpdate() {
      println "BEFORE UPDATE: " + this.getPersistentValue('users');
   }
}

class User implements Comparable<User> {
   String name
}

And the controller which has the following action:

class UserGroupController {
   def addUser() {
      UserGroup group = UserGroup.get(params.long('gid'))
      User user = User.get(params.long('uid'))

      group.addToUsers(user)
      group.save(failOnError:true, flush:true)
   }
}

The problem is that when beforeUpdate() is called, the users collection already contains the recently added user. So, seems that addTo() method doesn't trigger the beforeUpdate() event.

The same problem occurs when we're talking about isDirty() method. As the changes are applied before the beforeUpdate() is called, the collection is not recognized as dirty field.

Does anyone know how to change this? I'm writing a feature which tracks the history of changes for lots of different object, so I need to have access to the previous value in order to understand whether its value was changed or not.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Roman Reva
  • 55
  • 1
  • 7
  • Grails has a stack trace which might be useful in this situation, under conf DataSource.groovy you can set: logSql = true to see when the changes are being applied. – PJT Apr 02 '13 at 15:01
  • Thanks, i'm already using this feature for debug purposes! – Roman Reva Apr 04 '13 at 09:02

1 Answers1

0

I have had a similar issue, where things are being updated when I wasn't expecting them when I used the .get() on domain classes. I like to use .read() now because it wont update the database when I'm not expecting it to. Grails does a lot of sneaky things behind the sense which are helpful I think but can be a bit confusing.

PJT
  • 3,439
  • 5
  • 29
  • 40
  • 1
    Thanks, this can be helpful in case when you need to avoid unnecessary updates, which are done by Gorm. But this doesn't answer the question, how to get a persistent value for the collection, that was already changed by calling addTo() method but not flushed to the DB yet. – Roman Reva Apr 08 '13 at 16:41