0
votes

This question pertains to Grails 2.1.1. I have a domain object which contains 3 date fields which are set in the controller. I had a bug where the date being set in the controller was ignored and replaced with the current date

Oddly, this behaviour was only resolved when I renamed the corresponding fields in the domain object to have a 'date' suffix.

I would like to know:

  • if there is a particular naming convention that needs to be followed,
  • or whether there is a different underpinning issue I haven't understood (I know there is quite a bit of grails 'magic' that happens under the hood which frankly I am not too comfortable with)

The analysis and code samples are provided below:

Original domain object and controller - in this instance, the the values set for the 'dateCreated' and 'lastUpdated' are ignored and overridden by the system date.

class User {

String name
String title
String firstName
String lastName
Date companyCreationDate 

Date dateCreated //works when renamed to createdDate (and controller updated accordingly)
Date lastUpdated //works when renamed to lastUpdatedDate (and controller updated accordingly)

static mapping = {
    id column:'record_id'
}

static constraints = {
    id()
    title(blank: false, maxSize: 35)
    firstName(blank: false, minSize: 1, maxSize: 35)
    lastName(blank: false, minSize: 1, maxSize: 35)
}

}

class UserController {

static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
static df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)

def save() {
    def user = new User()
    user.name = params.name

    user.companyCreationDate = df.parse("2006-09-07 13:26:15");
    user.title = params._title
    user.firstName = params._fname
    user.lastName = params._lName

    user.creationDate = df.parse("2006-09-07 00:00:00");
    user.lastUpdatedDate = df.parse("2006-09-07 00:00:00");

    if (user.validate()){
        user.clearErrors();

        if (user.save(flush: true)) {
            flash.message = message(code: 'default.created.message', args: [message(code: 'registration.label', default: 'Registration'), user.id])
            redirect(action: "show", id: user.id)
        }
    }
    else
    {
        render(view: "create", model: [userInstance: user])
    }

After setting the tracing options in Hibernate, I noticed that this transformation was happening between saving the domain object (i.e. calling 'save(flush: true)' and Hibernate performing the persistence action.

Hibernate trace output

1

1 Answers

1
votes

You can disable this by setting autoTimestamp to false:Grails Doc