0

2 つのドメイン クラスの無方向の 1 対多の関係があります。

package net.peddn

class User {
    static hasMany = [texts: Text]
    String username 
}

package net.peddn

class Text {

    long creator
    String title

    static constraints = {
        creator( nullable: true )
    }   
}

私のユーザーコントローラは次のようになります:

package net.peddn

class UserController {

static scaffold = true

    def delete() {

        def userInstance = User.get(params.id)

        userInstance.texts.each { text ->
            text.creator = null
        }           

        userInstance.delete(flush: true)

}

私の BootStrap.groovy は次のようになります。

import net.peddn.Text
import net.peddn.User

class BootStrap {

    def init = { servletContext ->

    User user = new User(username: "username")

    user.save(flush: true)

    Text text1 = new Text(title: "titel 1", creator: user.id)

    Text text2 = new Text(title: "titel 2", creator: user.id)

    user.addToTexts(text1)

    user.addToTexts(text2)

    user.save(flush: true)

    }

    def destroy = {
    }

}

ユーザーを削除しようとすると、次のエラーが表示されます。

| Server running. Browse to http://localhost:8080/usertexts
| Error 2012-06-17 19:33:49,581 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver  - IllegalArgumentException occurred when processing request: [POST] /usertexts/user/index - parameters:
id: 1
_action_delete: Löschen
Stacktrace follows:
Message: null
    Line | Method
->>   21 | doCall    in net.peddn.UserController$_delete_closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|     19 | delete    in net.peddn.UserController
|   1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    603 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    722 | run . . . in java.lang.Thread

コードを次のように変更すると

text.creator = 0

UserController.groovy では完全に動作します。

ところで、このドメイン モデルを使用したのは、ユーザーが削除されるときに Text オブジェクトが削除されないようにするためです。しかし、Text オブジェクトの作成者も知りたいです。誰かがこの問題のより良い解決策を持っている場合は、私に知らせてください.

ありがとう!ピーター

4

2 に答える 2

0

ついに私は正しいヒントを見つけました。これはキャストの問題のようです。見る:

Grails2.0にアップグレードする際のGroovyプリミティブ型キャストの落とし穴

そこで、Textドメインクラスのプリミティブな「long」プロパティを「ボックス化された」バージョンの「Long」に変更しました。

package net.peddn

class Text {

    Long creator
    String title

    static constraints = {
        creator( nullable: true )
    }   
}

これで、プロパティをnullに設定できます。

Tomaszさん、ありがとうございました!

于 2012-06-18T10:01:59.857 に答える
0

現在の実装でこれが機能するかどうか試してください:

    def delete() {

        def userInstance = User.get(params.id)

        userInstance.texts.each { text ->
            userInstance.removeFromTexts(text)
        }           

        userInstance.delete(flush: true)
    }

ユーザーとテキストの双方向の関係が必要で、ユーザーが削除されたときにテキストを削除したくない場合は、この動作を変更できます。ここで、Hibernate のカスケードに関するドキュメント セクションを確認してください: custom cascades。次のようにマッピングを変更できます。

class User {
    static hasMany = [texts: Text]

    static mapping = {
        texts cascade: "save-update"
    }
}
于 2012-06-17T21:00:03.373 に答える