2012-11-22 29 views
8

मैं कई Grails 2.1 डोमेन कक्षाओं कि dateCreated और lastUpdated क्षेत्रों कि GORM स्वचालित रूप से प्रबंधन करता है, उदाहरण के लिए शामिल है:Grails दिनांक ओवरराइड केवल परीक्षण डेटा के लिए तैयार और अंतिम अद्यतन?

class Person { 
    Date dateCreated 
    Date lastUpdated 
    String name 
} 

मैं Grails स्वचालित रूप से रनटाइम पर इन क्षेत्रों में भरना चाहते हैं , लेकिन मैं यह भी करना चाहते कुछ परीक्षण डेटा बनाएं जहां मैं इन तिथियों के मानों को मैन्युअल रूप से परिभाषित कर सकता हूं। मुसीबत यह है कि Grails स्वचालित रूप से मूल्य निर्धारित करता है अगर इन क्षेत्रों में एक इंटरसेप्टर के साथ भी जब मैं विशेष रूप से उन्हें सेट किया है।

मैंने this SO question देखा है जो वर्णन करता है कि dateCreated में परिवर्तनों को कैसे अनुमति दें, लेकिन मुझे lastUpdated भी बदलना होगा। क्या यह संभव है?

+0

क्या आपने उस अन्य विधि का उपयोग करने का प्रयास किया था? मुझे लगता है कि यह काम नहीं किया? –

+0

@tim_yates, प्रश्न में लिंक की गई विधि मुझे मैन्युअल रूप से 'dateCreated' फ़ील्ड सेट करने की अनुमति देती है लेकिन' lastUpdated' फ़ील्ड नहीं। –

+0

क्या आपने परीक्षण किया था? ऐसा लगता है कि सभी टाइमस्टैम्प अक्षम हैं, इसलिए अंतिम अद्यतन शामिल है। –

उत्तर

16

ओह, मेरी गलती, दूसरे प्रश्न में दृष्टिकोण काम करता है, लेकिन सवाल की इकाई अलग से कहीं और सहेजी जा रही थी। यह भी लगता है कि आप एक स्पष्ट flush की जरूरत बनाने के लिए चीजें काम:

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) 
    } 
} 
2

यदि यह एक एकीकरण परीक्षण आप एक HQL अद्यतन बयान मैन्युअल lastUpdated स्थापित करने के लिए उपयोग कर सकते हैं।