使用Grails中的JSON帖子保存嵌套的对象列表失败

时间:2014-12-20 19:21:00

标签: json list rest grails post

示例应用程序:https://github.com/Hi-Fi/writetable-example-with-grails

在示例应用程序中,控制器在通过GSP页面使用或使用CURL表单发布时工作正常。带卷曲的命令:

curl "http://localhost:8080/junk/team/save" --data "name=team&players"%"5B0"%"5D.firstName=first&players"%"5B0"%"5D.lastName=last&players"%"5B0"%"5D.position=position&create=Create" --compressed.

问题在于使用JSON的相同请求,它创建相同的(根据dump())对象,但不能保存嵌套值。

使用SOAPUI(localhost:8080 / junk / api / rest)进行POST后:

{
    name: "Team name",
    players: [
        {
             firstName: "Player first name",
             lastName: "Player last name",
             position: "Player position"
        }
    ]
}

我得到错误:

| Error 2014-12-20 21:02:47,050 [http-bio-8080-exec-1] 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 junk.Player entry (don't flush the Session after an exception occurs)
Line | Method
->> 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    744 | run . . . in java.lang.Thread

即使存在此错误,父对象(团队)仍然保存。使用Hibernate4整个保存失败,因此更新它并没有帮助。

1 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是明确地将“团队”与每个“玩家”联系起来,如

team.players.each {it.team = team}

使用表单发布时,此步骤是自动生成的,但由于某些原因不适用于JSON。在JSON中创建Team对象后的Player对象:

<junk.Player@76f8539e firstName=first lastName=last position=position deleted=false errors=grails.validation.ValidationErrors: 0 errors $changedProperties=null id=null version=null team=null>

表格POST:

<junk.Player@1ba14c1b firstName=first lastName=last position=position deleted=false errors=grails.validation.ValidationErrors: 0 errors $changedProperties=null id=null version=null team=junk.Team : (unsaved)>

这可能不是“正确”的解决方案,所以我仍然很高兴听到嵌套的一对多列表是否有更好的解决方案。