I have the following User class:
class User implements Serializable {
private static final long serialVersionUID = 1
transient springSecurityService
String username
String password
String email
String firstName
String middleName
String lastName
...
}
I want to make a new domain object UserNameChange when the first, middle, or last name changes:
class UserNameChange {
User user
String firstName
String middleName
String lastName
}
I know I can do this in a transactional service, but it would be better if I could accomplish the same thing in the User class. How can I do this atomically? For instance, is "beforeUpdate" always done transactionally?
By default the domain class' methods are NOT transactional. So you would have to use withTransaction()
:
class User {
def beforeUpdate() {
if( ![ 'firstName', 'middleName', 'lastName' ].any{ isDirty it } ) return
User.withTransaction{
new UserNameChange( ... ).save()
}
}
}
You might also want to take a look at audit plugin