Question

I have several Grails 2.1 domain classes that include dateCreated and lastUpdated fields that GORM manages automatically, eg:

class Person {
    Date dateCreated
    Date lastUpdated
    String name
}

I want Grails to automatically fill in these fields at runtime, but I also want to create some test data where I can manually define the values of these dates. The trouble is that Grails automatically sets the values if these fields with an interceptor even when I have specifically set them.

I have seen this SO question which describes how to allow changes to dateCreated, but I need to change lastUpdated as well. Is this possible?

Était-ce utile?

La solution

Whoops, my mistake, the approach in the other question does work, but the entity in question was separately being saved somewhere else. It also seems that you need an explicit flush to make things work:

def withAutoTimestampSuppression(entity, closure) {
    toggleAutoTimestamp(entity, false)
    def result = closure()
    toggleAutoTimestamp(entity, true)
    result
}

def toggleAutoTimestamp(target, enabled) {
    def applicationContext = (ServletContextHolder.getServletContext()                                                           
                              .getAttribute(ApplicationAttributes.APPLICATION_CONTEXT))

    def closureInterceptor = applicationContext.getBean("eventTriggeringInterceptor")
    def datastore = closureInterceptor.datastores.values().iterator().next()
    def interceptor = datastore.getEventTriggeringInterceptor()

    def listener = interceptor.findEventListener(target)
    listener.shouldTimestamp = enabled
    null
}

def createTestPerson() {

    def luke = new Person(name: "Luke Skywalker")
    withAutoTimestampSuppression(luke) {

        def lastWeek = new Date().minus(7)
        luke.dateCreated = lastWeek
        luke.lastUpdated = lastWeek
        luke.save(failOnError: true, flush: true)
    }
}

Autres conseils

If it is an integration test you can use an hql update statement to manually set lastUpdated.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top