2012-10-08 26 views
1

如何在域中導入服務?如何在域中導入服務?

它有一個字段,我需要填寫一個協議字段。該協議是自動生成的,併爲這一代創建了一項服務排除事項。

在方法'AfterInsert'中插入對該服務的調用,該服務自動填充該字段。

我把引導創建一些對象,這些對象需要用這個協議填充到你的字段中。但是,顯然由於在「域」中使用「服務」而出現錯誤。任何人都可以幫我嗎?

class Post { 

    static transient postService 

    String conteudo 
    Date dataCriacao = new Date() 
    String protocolo 

    static constraints = { 

     dataCriacao(nullable:false, blank:false) 
     conteudo nullable:false, blank: false 
     protocolo nullable: true, blank: true 

    } 

    static mapping = { 
     conteudo type: 'text' 
     sort dataCriacao:"desc" 
    } 

    def afterInsert(){ 
     if(!this.protocolo){     
      registraProtocolo() 
     } 
    } 

    protected void registraProtocolo() { 
     postService.teste(this) 
    } 
} 

Error: ERROR hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) 
Message: null id in com.app.post.Post entry (don't flush the Session after an exception occurs) 
    Line | Method 
->> 105 | doCall    in org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2 

Message: null id in com.app.post.Post entry (don't flush the Session after an exception occurs) 
    Line | Method 
->> 105 | doCall    in org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|  27 | recInsertProtocolo in com.app.post.PostService 
|  83 | teste . . . . . . in  '' 
| 117 | registraProtocolo in com.app.post.Post 
+0

什麼是postService.teste的內容? –

+0

只是一個函數更改協議屬性: 高清泰斯特(後後){ post.protocolo =「START」 } – isilva

回答

1

問題解決了!這是一個邏輯問題。該服務自動將setados設置爲'transational = true',使用AfterInsert時會由於該服務的此功能而發生錯誤。但是如果你使用閉包'withNewSession',這個問題就解決了,一旦新會話滿足'transational'的要求,就可以改變服務對象的屬性。剛拿到我的域名是這樣的:

AfterInsert def() { 

    if (! this.protocolo) { 

      Post.withNewSession 
      { 

        registraProtocolo() 


      } 

    } 

} 

protected void registraProtocolo() { 
    postService.teste (this) 
} 

謝謝大家的幫助

For those who want more information down a JIRA who helped me in this solution (read the comments)

4

postService不應該是一成不變的,它應該是簡單的

transient postService 
+0

我和** transcient嘗試**,甚至宣佈服務爲* * def **但是當我嘗試更改數據字段時發生錯誤。如果我把該函數和實現其他服務只有沒有問題,但如果該函數更改同一對象的屬性是'AfterInsert'說ID爲空**消息:空ID在條目com.app.post。發佈(發生異常後不要刷新會話)**。所以我不知道如何讓服務更改對象的屬性而不會發生此錯誤。 – isilva

0
+0

雖然在主要文檔中沒有說明,但如果您需要將該類在將來可序列化(例如,如果您想要開始使用[web flow](http),那麼在您的自動佈線服務中使用'transient' ://grails.org/doc/latest/guide/theWebLayer.html#webflow))。 –

+0

我讀過文檔,但奇怪的是,在沒有文檔的情況下,對象的屬性發生了變化,並且當我使用服務來更改'afterInser'中發生的屬性錯誤時。我的印象是,當運行'AfterInsert'時,hibernate不會將信息保存在數據庫中。 – isilva

+0

請注意,條目com.app.post.Post中的錯誤消息爲空id(發生異常後不刷新會話)。 – isilva