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 オブジェクトの作成者も知りたいです。誰かがこの問題のより良い解決策を持っている場合は、私に知らせてください.
ありがとう!ピーター